본문으로 이동

코드해킹: 두 판 사이의 차이

lse
 
(사용자 2명의 중간 판 5개는 보이지 않습니다)
160번째 줄: 160번째 줄:
: [[file:ls_gpt_01.jpg|700px]]
: [[file:ls_gpt_01.jpg|700px]]


<nowiki>
<code>
# list_window_objects.py
# list_window_objects.py


import pywinauto
import pywinauto
233번째 줄: 233번째 줄:
     print(f"An unexpected error occurred: {e}")
     print(f"An unexpected error occurred: {e}")


</nowiki>
</code>
 
===설명 사항===
이 코드는 **Pywinauto** 라이브러리를 사용하여 특정 창을 찾고, 그 창과 상호작용하는 프로그램입니다. 아래는 코드의 주요 부분에 대한 설명입니다:
 
1. **라이브러리 임포트**:
    ```python
    import pywinauto
    import sys
    import find_ls_gpt
    ```
 
2. **창 찾기**:
    ```python
    target_title = "LS GPT | Microsoft Teams"
    hwnd = find_ls_gpt.find_window_by_title_pywinauto(target_title)
    ```
    `find_ls_gpt` 모듈을 사용하여 제목이 "LS GPT | Microsoft Teams"인 창의 핸들(HWND)을 찾습니다.
 
3. **창 연결**:
    ```python
    app = pywinauto.Application(backend="uia").connect(handle=hwnd)
    window = app.window(handle=hwnd)
    ```
    찾은 핸들을 사용하여 해당 창과 연결합니다. `backend="uia"`는 현대적인 앱(예: Microsoft Teams)에 사용됩니다.
 
4. **컨트롤 식별자 출력**:
    ```python
    print("\nWindow Objects (Control Identifiers):")
    # window.print_control_identifiers() # 주석 처리
    ```
    창의 컨트롤 식별자를 출력합니다. 주석 처리된 부분은 실제로 식별자를 출력하는 코드입니다.
 
5. **Edit 컨트롤 찾기 및 텍스트 설정**:
    ```python
    edit_control = window.child_window(title="", control_type="Edit")
    user_input = input("Enter text for the Edit control: ")
    edit_control.set_text(user_input)
    ```
    Edit 컨트롤을 찾아 사용자 입력을 설정합니다.
 
6. **Button 컨트롤 찾기 및 클릭**:
    ```python
    button_control = window.child_window(title="up arrow", control_type="Button")
    button_control.click()
    ```
    Button 컨트롤을 찾아 클릭합니다.
 
7. **예외 처리**:
    ```python
    except pywinauto.findwindows.ElementNotFoundError:
        print(f"Error: Window with HWND {hwnd} not found. Make sure the window is open and the HWND is correct.")
    except IndexError:
        print("Error: Please provide the HWND as a command-line argument.")
        print("Usage: python list_window_objects.py <HWND>")
    except ValueError:
        print("Error: Invalid HWND provided. HWND must be an integer.")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")
    ```
    다양한 예외 상황을 처리하여 사용자에게 적절한 오류 메시지를 출력합니다.
 
 
 


==출력 제어==
==출력 제어==
240번째 줄: 303번째 줄:
따라서, 끝을 찾아서 출력하는 모델을 사용하거나, 맨 아래 있는 복사 버튼을 이용하여 해당 내용 복사 후, 콘솔에 뿌려주는 방식적용 필요
따라서, 끝을 찾아서 출력하는 모델을 사용하거나, 맨 아래 있는 복사 버튼을 이용하여 해당 내용 복사 후, 콘솔에 뿌려주는 방식적용 필요


: [[file:ls_gpt_02.jpg|700px]]


<code>
<code>
248번째 줄: 312번째 줄:


</code>
</code>
=Dolibarr ERP/CRM=
코드 생성 관련




[[category: AI]]
[[category: AI]]

2025년 4월 29일 (화) 01:24 기준 최신판

AI Agent를 이용한 코드 해킹 - 코드 분석이라는 이야기임.

LS GPT의 경우, 기업 라이선스 (혹은 재 라이선스) 제품

wrtn.ai 와 같은 회사에서, ai환경을 이용하고, 인터페이스 부분만 Teams 형태로 바꾼 것임.

실제로, 윈도우에서 보면, Chrome의 자동화로 검색됨.

윈도우 핸들러 얻기

[편집 | 원본 편집]
  1. LS GPT가 기동되는 상태에서, 윈도우 핸들러를 얻는다.
  2. Objects로 창 내의 아이템을 확인한다.

  • 코드

윈도우 title로 찾아서 윈도우 핸들러 얻기

  1. find_ls_gpt.py

import win32gui import pywinauto

def window_enum_handler(hwnd, resultList):

   title = win32gui.GetWindowText(hwnd)
   resultList.append((hwnd, title))

def find_window_by_title(title_text):

   windows = []
   win32gui.EnumWindows(window_enum_handler, windows)
   for hwnd, title in windows:
       if win32gui.IsWindowVisible(hwnd):
           print(f"HWND: {hwnd}, Title: {title}")
           if title_text in title:
               print(f"Found: HWND: {hwnd}, Title: {title}")

def find_window_by_title_pywinauto(title):

   try:
       app = pywinauto.Application(backend="uia").connect(title=title)
       window = app.window(title=title)
       return window.handle
   except pywinauto.findwindows.ElementNotFoundError:
       return None

if __name__ == '__main__':

   target_title = "LS GPT | Microsoft Teams"
   hwnd = find_window_by_title_pywinauto(target_title)
   if hwnd:
       print(f"Found window with HWND: {hwnd}")
   else:
       print(f"Window with title '{target_title}' not found.")


  • LS GPT창의 Object list 받아오기

LS GPT에서 Object를 모두 찾는다.

Web의 경우, CSS Selector로 구분할 수 있다.

기타 Power Automate나 uiPATH를 통해서, 숨겨져 있는 selector를 구분할 수 있다.
추가로 DOM 구조를 확인해 보는 것도 괜찮을 듯.


  1. test02.py

import pywinauto import sys import find_ls_gpt

try:

   # Get HWND from find_ls_gpt.py
   target_title = "LS GPT | Microsoft Teams"
   hwnd = find_ls_gpt.find_window_by_title_pywinauto(target_title)
   if hwnd is None:
       print(f"Error: Window with title '{target_title}' not found.")
       sys.exit(1)
   print(f"Attempting to connect to window with HWND: {hwnd}")
   # Connect to the application/window using the HWND
   # Use backend="uia" for modern apps like Teams, or "win32" for older apps
   app = pywinauto.Application(backend="uia").connect(handle=hwnd)
   print("Successfully connected to the application.")
   # Get the main window
   window = app.window(handle=hwnd)
   print("Successfully retrieved the window.")
   # Print control identifiers (object list)
   print("\nWindow Objects (Control Identifiers):")
   window.print_control_identifiers()
   print("\nSuccessfully printed control identifiers.")

except pywinauto.findwindows.ElementNotFoundError:

   print(f"Error: Window with HWND {hwnd} not found. Make sure the window is open and the HWND is correct.")

except IndexError:

   print("Error: Please provide the HWND as a command-line argument.")
   print("Usage: python list_window_objects.py <HWND>")

except ValueError:

   print("Error: Invalid HWND provided. HWND must be an integer.")

except Exception as e:

   print(f"An unexpected error occurred: {e}")

  • Object list 발췌

<coide>

  |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |
  |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    | Static - 'Large Language Model은 컴퓨팅 기술의 발전과 함께 많은 분야에 혁신을 가져오고 있으며, 인간과 기계 간의 상호작용을 더욱 자연스럽고 효과적으로 만들어 줍니다. 궁금한 점이 더 있으시면 언제든지 질문해 주세요!'    (L857, T909, R1802, B964)
  |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    | ['Static47', 'Large Language Model은 컴퓨팅 기술의 발전과 함께 많은 분야에 혁신을 가져오고 있으며, 인간과 기계 간의 상호작용을 더욱 자연스럽고 효과적으로 만들어 줍니다. 궁금한 점이 더 있으시면 언제든지 질문해 주세요!Static', 'Large Language Model은 컴퓨팅 기술의 발전과 함께 많은 분야에 혁신을 가져오고 있으며, 인간과 기계 간의 상호작용을 더욱 자연스럽고 효과적으로 만들어 줍니다. 궁금한 점이 더 있으시면 언제든지 질문해 주세요!']
  |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    | child_window(title="Large Language Model은 컴퓨팅 기술의 발전과 함께 많은 분야에 혁신을 가져오고 있으며, 인간과 기계 간의 상호작용을 더욱 자연스럽고 효과적으로 만들어 줍니다. 궁금한 점이 더 있으시면 언제든지 질문해 주세요!", control_type="Text")
  |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |
  |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    | Button -     (L835, T994, R881, B1040)
  |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    | ['Large Language Model은 컴퓨팅 기술의 발전과 함께 많은 분야에 혁신을 가져오고 있으며, 인간과 기계 간의 상호작용을 더욱 자연스럽고 효과적으로 만들어 줍니다. 궁금한 점이 더 있으시면 언제든지 질문해 주세요!Button', 'Button10']
  |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |
  |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    | Image -     (L841, T1001, R874, B1034)
  |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    | ['Large Language Model은 컴퓨팅 기술의 발전과 함께 많은 분야에 혁신을 가져오고 있으며, 인간과 기계 간의 상호작용을 더욱 자연스럽고 효과적으로 만들어 줍니다. 궁금한 점이 더 있으시면 언제든지 질문해 주세요!Image', 'Image110']
  |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |
  |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    | Button - '현재 GPT와 새 대화'    (L838, T1113, R1022, B1168)
  |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    | ['현재 GPT와 새 대화', '현재 GPT와 새 대화Button', 'Button11']
  |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    | child_window(title="현재 GPT와 새 대화", control_type="Button")
  |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |
  |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    | Button - '다른 GPT와 새 대화'    (L1032, T1113, R1216, B1168)
  |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    | ['다른 GPT와 새 대화', 'Button12', '다른 GPT와 새 대화Button']
  |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    | child_window(title="다른 GPT와 새 대화", control_type="Button")
  |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |
  |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    | Image - 'light-bulb'    (L1242, T1124, R1272, B1155)
  |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    | ['Image111', 'light-bulbImage', 'light-bulb']
  |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    | child_window(title="light-bulb", control_type="Image")
  |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |
  |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    | Static - '앞 질문에 이어지는 질문이 아닐 경우, 새 대화로 물으면 대답을 더 잘합니다.'    (L1282, T1128, R1834, B1151)
  |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    | ['앞 질문에 이어지는 질문이 아닐 경우, 새 대화로 물으면 대답을 더 잘합니다.', 'Static48', '앞 질문에 이어지는 질문이 아닐 경우, 새 대화로 물으면 대답을 더 잘합니다.Static']
  |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    | child_window(title="앞 질문에 이어지는 질문이 아닐 경우, 새 대화로 물으면 대답을 더 잘합니다.", control_type="Text")
  |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |
  |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    | Edit - ''    (L840, T1181, R1778, B1247)
  |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    | ['Large Language Model은 컴퓨팅 기술의 발전과 함께 많은 분야에 혁신을 가져오고 있으며, 인간과 기계 간의 상호작용을 더욱 자연스럽고 효과적으로 만들어 줍니다. 궁금한 점이 더 있으시면 언제든지 질문해 주세요!Edit', 'Edit', '앞 질문에 이어지는 질문이 아닐 경우, 새 대화로 물으면 대답을 더 잘합니다.Edit']
  |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    | child_window(title="", control_type="Edit")
  |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |
  |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    | Button - 'up arrow'    (L1777, T1181, R1842, B1250)
  |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    | ['up arrow', 'Button13', 'up arrowButton', 'up arrow0', 'up arrow1']
  |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    | child_window(title="up arrow", control_type="Button")
  |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |
  |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    | Image - 'up arrow'    (L1790, T1196, R1829, B1235)
  |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    | ['up arrow2', 'up arrowImage', 'Image112']
  |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    | child_window(title="up arrow", control_type="Image")
  |    |    |    |    |    |    |    |    |    |    |    |    |    |

* 입력은 EDIT 컨트롤
* 엔터는 화살표
* 답변은 copy clip board 사용  - Group으로 생성되는데 끝을 알지 못함 (Power Automate)

LS GPT에 질문 넘기기

[편집 | 원본 편집]

edit 오브젝트에 내용을 넘기고, 결과를 LS GPT에서 출력함

# list_window_objects.py

import pywinauto import sys import find_ls_gpt

try:

   # Get HWND from find_ls_gpt.py
   target_title = "LS GPT | Microsoft Teams"
   hwnd = find_ls_gpt.find_window_by_title_pywinauto(target_title)
   if hwnd is None:
       print(f"Error: Window with title '{target_title}' not found.")
       sys.exit(1)
   print(f"Attempting to connect to window with HWND: {hwnd}")
   # Connect to the application/window using the HWND
   # Use backend="uia" for modern apps like Teams, or "win32" for older apps
   app = pywinauto.Application(backend="uia").connect(handle=hwnd)
   print("Successfully connected to the application.")
   # Get the main window
   window = app.window(handle=hwnd)
   print("Successfully retrieved the window.")
   # Print control identifiers (object list)
   print("\nWindow Objects (Control Identifiers):")
   # window.print_control_identifiers() # 주석 처리
   print("\nSuccessfully printed control identifiers.")
   # Find the Edit control
   edit_control = window.child_window(title="", control_type="Edit") # Edit control의 title이 "" 임을 확인
   edit_control.set_text("생성형 AI는 무엇이야?")
   print("Successfully set text to the Edit control.")
   # Find the Button control
   button_control = window.child_window(title="up arrow", control_type="Button")
   button_control.click()
   print("Successfully clicked the Button control.")
   # Wait for the window content to change (adjust timeout if needed)
   window.wait('ready', timeout=10)
   print("Window content has changed.")
   # Find the Static control (adjust title if needed)
   # groupbox_control = window.child_window(control_type="Group") # 여러개라서 특정할 수 없음
   # 특정 GroupBox를 찾기 위해 title을 사용
   groupbox_control = window.child_window(title="Chat GPT와 일합니다.", control_type="GroupBox")
   print("Successfully found the GroupBox control.")

   # 다른 방법
   # Image - 은 카피 버튼이다.
   # 윈도우 변화가 끝나면,Button - 을 찾고, 버튼 클릭 --> 클립보드에 복사됨, 해당 파일 가져오기임
   # 버튼 여러개 중에서 맨 아래 것? 확인 필요


   # Print the text of the GroupBox control
   print("\nGroupBox Content:")
   print(groupbox_control.texts())
   print("\nSuccessfully printed GroupBox content.")

except pywinauto.findwindows.ElementNotFoundError:

   print(f"Error: Window with HWND {hwnd} not found. Make sure the window is open and the HWND is correct.")

except IndexError:

   print("Error: Please provide the HWND as a command-line argument.")
   print("Usage: python list_window_objects.py <HWND>")

except ValueError:

   print("Error: Invalid HWND provided. HWND must be an integer.")

except Exception as e:

   print(f"An unexpected error occurred: {e}")

설명 사항

[편집 | 원본 편집]

이 코드는 **Pywinauto** 라이브러리를 사용하여 특정 창을 찾고, 그 창과 상호작용하는 프로그램입니다. 아래는 코드의 주요 부분에 대한 설명입니다:

1. **라이브러리 임포트**:

   ```python
   import pywinauto
   import sys
   import find_ls_gpt
   ```

2. **창 찾기**:

   ```python
   target_title = "LS GPT | Microsoft Teams"
   hwnd = find_ls_gpt.find_window_by_title_pywinauto(target_title)
   ```
   `find_ls_gpt` 모듈을 사용하여 제목이 "LS GPT | Microsoft Teams"인 창의 핸들(HWND)을 찾습니다.

3. **창 연결**:

   ```python
   app = pywinauto.Application(backend="uia").connect(handle=hwnd)
   window = app.window(handle=hwnd)
   ```
   찾은 핸들을 사용하여 해당 창과 연결합니다. `backend="uia"`는 현대적인 앱(예: Microsoft Teams)에 사용됩니다.

4. **컨트롤 식별자 출력**:

   ```python
   print("\nWindow Objects (Control Identifiers):")
   # window.print_control_identifiers() # 주석 처리
   ```
   창의 컨트롤 식별자를 출력합니다. 주석 처리된 부분은 실제로 식별자를 출력하는 코드입니다.

5. **Edit 컨트롤 찾기 및 텍스트 설정**:

   ```python
   edit_control = window.child_window(title="", control_type="Edit")
   user_input = input("Enter text for the Edit control: ")
   edit_control.set_text(user_input)
   ```
   Edit 컨트롤을 찾아 사용자 입력을 설정합니다.

6. **Button 컨트롤 찾기 및 클릭**:

   ```python
   button_control = window.child_window(title="up arrow", control_type="Button")
   button_control.click()
   ```
   Button 컨트롤을 찾아 클릭합니다.

7. **예외 처리**:

   ```python
   except pywinauto.findwindows.ElementNotFoundError:
       print(f"Error: Window with HWND {hwnd} not found. Make sure the window is open and the HWND is correct.")
   except IndexError:
       print("Error: Please provide the HWND as a command-line argument.")
       print("Usage: python list_window_objects.py <HWND>")
   except ValueError:
       print("Error: Invalid HWND provided. HWND must be an integer.")
   except Exception as e:
       print(f"An unexpected error occurred: {e}")
   ```
   다양한 예외 상황을 처리하여 사용자에게 적절한 오류 메시지를 출력합니다.



출력 제어

[편집 | 원본 편집]

Control이 Group으로 되어 있는데, 리스트 구조형으로 끝을 알 수 없는 자료형

따라서, 끝을 찾아서 출력하는 모델을 사용하거나, 맨 아래 있는 복사 버튼을 이용하여 해당 내용 복사 후, 콘솔에 뿌려주는 방식적용 필요

   # 다른 방법
   # Image - 은 카피 버튼이다.
   # 윈도우 변화가 끝나면,Button - 을 찾고, 버튼 클릭 --> 클립보드에 복사됨, 해당 파일 가져오기임
   # 버튼 여러개 중에서 맨 아래 것? 확인 필요

Dolibarr ERP/CRM

[편집 | 원본 편집]

코드 생성 관련