|
| 1 | +import json |
| 2 | +from openai import OpenAI |
| 3 | +import subprocess |
| 4 | +import shutil |
| 5 | +import httpx |
| 6 | +import base64 |
| 7 | +import re |
| 8 | +import os |
| 9 | +import openai |
| 10 | +picture_folder = "DeclarUI\Dataset" |
| 11 | +ptg_prompt_path = "DeclarUI\Scripts\data_preprocess\ptg_construction\PTG_Prompt.txt" |
| 12 | + |
| 13 | +def encode_image(image_path): |
| 14 | + with open(image_path, "rb") as image_file: |
| 15 | + return base64.b64encode(image_file.read()).decode('utf-8') |
| 16 | + |
| 17 | + |
| 18 | +def ptg_generate(image_dir, category, app_name, content): |
| 19 | + image_files = [] |
| 20 | + app_img_folder = os.path.join(image_dir, category, app_name) |
| 21 | + |
| 22 | + files = os.listdir(app_img_folder) |
| 23 | + png_files = [f for f in files if f.endswith('.png')] |
| 24 | + png_file_names = [f.split('.')[0] for f in png_files] |
| 25 | + content.format(node_id_list=png_file_names) |
| 26 | + for file in png_files: |
| 27 | + image_files.append(encode_image(os.path.join(app_img_folder, file))) |
| 28 | + |
| 29 | + client = OpenAI( |
| 30 | + base_url="https://api.xty.app/v1", |
| 31 | + api_key="your_api_key", |
| 32 | + http_client=httpx.Client( |
| 33 | + base_url="https://api.xty.app/v1", |
| 34 | + follow_redirects=True, |
| 35 | + ), |
| 36 | + ) |
| 37 | + text_dic = { |
| 38 | + "type":"text", |
| 39 | + "text":content |
| 40 | + } |
| 41 | + img_dic_list =[] |
| 42 | + for base64_img_before in image_files: |
| 43 | + pic_type = "png" |
| 44 | + img_content_template = { |
| 45 | + "type":"image_url", |
| 46 | + "image_url":{ |
| 47 | + "url": f"data:image/{pic_type};base64,{base64_img_before}" |
| 48 | + } |
| 49 | + } |
| 50 | + img_dic_list.append(img_content_template) |
| 51 | + response = "" |
| 52 | + content_list = [text_dic] + img_dic_list |
| 53 | + completion = client.chat.completions.create( |
| 54 | + model="claude-3.5-sonnet", |
| 55 | + messages=[ |
| 56 | + {"role": "user", |
| 57 | + "content": content_list |
| 58 | + }, |
| 59 | + ], |
| 60 | + ) |
| 61 | + response = response + completion.choices[0].message.content + '\n' |
| 62 | + return response |
| 63 | + |
| 64 | + |
| 65 | +if __name__ == "__main__": |
| 66 | + category = "" |
| 67 | + app_name = "" |
| 68 | + with open(ptg_prompt_path, 'r', encoding='utf-8') as f: |
| 69 | + ptg_prompt = f.read() |
| 70 | + res = ptg_generate(picture_folder,category,app_name,ptg_prompt) |
| 71 | + |
| 72 | + |
| 73 | + |
0 commit comments