Update app.py
Browse files7 unmodified lines89101112131452 unmodified lines67686970717273747533 unmodified lines10911011111211311411511611711811912012112212312412512612712812913013117 unmodified lines14915015115215315415515615715815916016116216316416516623 unmodified lines1901911921931941951968 unmodified lines20520620720820921021121226 unmodified lines23924024124224324424524624724824925018 unmodified lines2692702712722732742752762772782792802812822832842852862872882892902912922934 unmodified lines298299300301302303304305306127 unmodified lines43443543643743843944044144244344444544644744844945045145214 unmodified lines46746846947047147247356 unmodified lines5305315325337 unmodified linesimport osfrom typing import Dict, List, Tupleimport asyncioimport aiohttp# Initialize body estimation modelbody_estimation = Body('model/body_pose_model.pth')52 unmodified linesnew_image = cv2.cvtColor(new_image, cv2.COLOR_RGBA2BGRA)return new_imageasync def generate_pose_from_llm(prompt: str) -> Dict:"""LLM을 사용하여 텍스트 프롬프트로부터 포즈 데이터를 생성"""system_prompt = """You are an expert in human pose generation. Given a description, generate precise OpenPose keypoint coordinates.33 unmodified lines}try:async with aiohttp.ClientSession() as session:async with session.post(FIREWORKS_API_URL, headers=headers, json=payload) as response:if response.status == 200:data = await response.json()content = data['choices'][0]['message']['content']# Extract JSON from responseimport rejson_match = re.search(r'\{.*\}', content, re.DOTALL)if json_match:pose_data = js.loads(json_match.group())return pose_dataelse:# Fallback to templatereturn generate_template_pose(prompt)else:return generate_template_pose(prompt)except Exception as e:print(f"LLM Error: {e}")return generate_template_pose(prompt)17 unmodified linesfor i in range(18):if i == 0: # Nosecandidate.append([256, 100, 1.0])elif part_name := next((k for k, v in BODY_PARTS.items() if v == i), None):if part_name in template["keypoints"]:x, y = template["keypoints"][part_name]candidate.append([x, y, 1.0])else:# Estimate position based on nearby keypointscandidate.append([256, 256, 0.0])else:candidate.append([0, 0, 0.0])# Create subset (connection information)subset = [[i for i in range(18) if candidate[i][2] > 0] + [18.0, 18]]return {"candidate": candidate, "subset": subset}23 unmodified lines}try:response = requests.post(FIREWORKS_API_URL, headers=headers, json=payload)if response.status_code == 200:data = response.json()content = data['choices'][0]['message']['content']8 unmodified linesreturn current_pose# FastAPI setupwith open("static/poseEditor.js", "r") as f:file_contents = f.read()app = FastAPI()26 unmodified linesreturn responsedef candidate_to_json_string(arr):a = [f'[{x:.2f}, {y:.2f}]' for x, y, *_ in arr]return '[' + ', '.join(a) + ']'def subset_to_json_string(arr):arr_str = ','.join(['[' + ','.join([f'{num:.2f}' for num in row]) + ']' for row in arr])return '[' + arr_str + ']'def estimate_body(source):if source == None:18 unmodified linesjsonText = "{ \"candidate\": " + candidate_to_json_string(candidate) + ", \"subset\": " + subset_to_json_string(subset) + " }"return f"""{image.width}px x {image.height}px, {subset.shape[0]} individual(s)""", jsonTextasync def generate_pose_from_text(prompt: str, use_llm: bool = True):"""텍스트 프롬프트로부터 포즈 생성"""if use_llm and FIREWORKS_API_KEY != "YOUR_API_KEY_HERE":pose_data = await generate_pose_from_llm(prompt)else:pose_data = generate_template_pose(prompt)# Format for the pose editorif isinstance(pose_data['candidate'], list):candidate_str = candidate_to_json_string(pose_data['candidate'])else:candidate_str = js.dumps(pose_data['candidate'])if isinstance(pose_data['subset'], list):subset_str = subset_to_json_string(pose_data['subset'])else:subset_str = js.dumps(pose_data['subset'])return "{ \"candidate\": " + candidate_str + ", \"subset\": " + subset_str + " }"4 unmodified lines# Gradio interfacewith gr.Blocks(css="""button { min-width: 80px; }.prompt-box { border: 2px solid #667eea; border-radius: 8px; padding: 10px; }.llm-status { color: #667eea; font-weight: bold; }""") as demo:gr.Markdown("""127 unmodified lines)# LLM generation eventsasync def handle_generate(prompt, use_llm):if not prompt:return None, "⚠️ Please enter a pose description"try:status = "🔄 Generating pose with AI..." if use_llm else "🔄 Using template..."yield None, statuspose_json = await generate_pose_from_text(prompt, use_llm)yield pose_json, "✅ Pose generated successfully!"except Exception as e:yield None, f"❌ Error: {str(e)}"generate_btn.click(fn=handle_generate,14 unmodified linesoutputs=[refinement_prompt])async def handle_refine(current_json, refinement):if not current_json or not refinement:return None, "⚠️ Need current pose and refinement instructions"56 unmodified linesdemo.load(fn=check_api_status, outputs=[llm_status])gr.mount_gradio_app(app, demo, path="/")7 unmodified lines891011121352 unmodified lines66676869707172737433 unmodified lines10810911011111211311411511611711811912012112212312412512612712817 unmodified lines14614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517623 unmodified lines2002012022032042052068 unmodified lines21521621721821922022122222322422526 unmodified lines25225325425525625725825926026126226326426526626726826927027127227327418 unmodified lines2932942952962972982993003013023033043053063073083093104 unmodified lines315316317318319320321322323127 unmodified lines45145245345445545645745845946046146246346446546614 unmodified lines48148248348448548648756 unmodified lines5445455465475485495505515525537 unmodified linesimport osfrom typing import Dict, List, Tupleimport asyncio# Initialize body estimation modelbody_estimation = Body('model/body_pose_model.pth')52 unmodified linesnew_image = cv2.cvtColor(new_image, cv2.COLOR_RGBA2BGRA)return new_imagedef generate_pose_from_llm_sync(prompt: str) -> Dict:"""LLM을 사용하여 텍스트 프롬프트로부터 포즈 데이터를 생성 (동기 버전)"""system_prompt = """You are an expert in human pose generation. Given a description, generate precise OpenPose keypoint coordinates.33 unmodified lines}try:response = requests.post(FIREWORKS_API_URL, headers=headers, json=payload, timeout=30)if response.status_code == 200:data = response.json()content = data['choices'][0]['message']['content']# Extract JSON from responseimport rejson_match = re.search(r'\{.*\}', content, re.DOTALL)if json_match:pose_data = js.loads(json_match.group())return pose_dataelse:return generate_template_pose(prompt)else:return generate_template_pose(prompt)except Exception as e:print(f"LLM Error: {e}")return generate_template_pose(prompt)17 unmodified linesfor i in range(18):if i == 0: # Nosecandidate.append([256, 100, 1.0])elif i == 14: # REyecandidate.append([246, 90, 1.0])elif i == 15: # LEyecandidate.append([266, 90, 1.0])elif i == 16: # REarcandidate.append([236, 95, 1.0])elif i == 17: # LEarcandidate.append([276, 95, 1.0])else:# Find part name for this indexpart_name = Nonefor name, idx in BODY_PARTS.items():if idx == i:part_name = namebreakif part_name and part_name in template["keypoints"]:x, y = template["keypoints"][part_name]candidate.append([x, y, 1.0])else:candidate.append([256, 256, 0.0])# Create subset (connection information)valid_indices = [i for i in range(18) if candidate[i][2] > 0]subset = [valid_indices + [float(len(valid_indices)), len(valid_indices)]]return {"candidate": candidate, "subset": subset}23 unmodified lines}try:response = requests.post(FIREWORKS_API_URL, headers=headers, json=payload, timeout=30)if response.status_code == 200:data = response.json()content = data['choices'][0]['message']['content']8 unmodified linesreturn current_pose# FastAPI setuptry:with open("static/poseEditor.js", "r") as f:file_contents = f.read()except:file_contents = "console.log('PoseEditor.js not found');"app = FastAPI()26 unmodified linesreturn responsedef candidate_to_json_string(arr):if isinstance(arr, list):a = []for item in arr:if len(item) >= 2:x, y = item[0], item[1]a.append(f'[{float(x):.2f}, {float(y):.2f}]')return '[' + ', '.join(a) + ']'return '[]'def subset_to_json_string(arr):if isinstance(arr, np.ndarray):arr_str = ','.join(['[' + ','.join([f'{num:.2f}' for num in row]) + ']' for row in arr])return '[' + arr_str + ']'elif isinstance(arr, list):arr_str = ','.join(['[' + ','.join([f'{float(num):.2f}' for num in row]) + ']' for row in arr])return '[' + arr_str + ']'return '[]'def estimate_body(source):if source == None:18 unmodified linesjsonText = "{ \"candidate\": " + candidate_to_json_string(candidate) + ", \"subset\": " + subset_to_json_string(subset) + " }"return f"""{image.width}px x {image.height}px, {subset.shape[0]} individual(s)""", jsonTextdef generate_pose_from_text(prompt: str, use_llm: bool = True):"""텍스트 프롬프트로부터 포즈 생성 (동기 버전)"""if use_llm and FIREWORKS_API_KEY != "YOUR_API_KEY_HERE":pose_data = generate_pose_from_llm_sync(prompt)else:pose_data = generate_template_pose(prompt)# Format for the pose editorcandidate_str = candidate_to_json_string(pose_data['candidate'])subset_str = subset_to_json_string(pose_data['subset'])return "{ \"candidate\": " + candidate_str + ", \"subset\": " + subset_str + " }"4 unmodified lines# Gradio interfacewith gr.Blocks(css="""button {{ min-width: 80px; }}.prompt-box {{ border: 2px solid #667eea; border-radius: 8px; padding: 10px; }}.llm-status {{ color: #667eea; font-weight: bold; }}""") as demo:gr.Markdown("""127 unmodified lines)# LLM generation eventsdef handle_generate(prompt, use_llm):if not prompt:return None, "⚠️ Please enter a pose description"try:status = "🔄 Generating pose with AI..." if use_llm else "🔄 Using template..."pose_json = generate_pose_from_text(prompt, use_llm)return pose_json, "✅ Pose generated successfully!"except Exception as e:return None, f"❌ Error: {str(e)}"generate_btn.click(fn=handle_generate,14 unmodified linesoutputs=[refinement_prompt])def handle_refine(current_json, refinement):if not current_json or not refinement:return None, "⚠️ Need current pose and refinement instructions"56 unmodified linesdemo.load(fn=check_api_status, outputs=[llm_status])# Mount Gradio app to FastAPIgr.mount_gradio_app(app, demo, path="/")# For running the appif __name__ == "__main__":import uvicornuvicorn.run(app, host="0.0.0.0", port=7860)
app.py+77-57