import os import openai import gradio as gr ################################### # (필수) OpenAI API 클라이언트 설정 ################################### openai.api_key = os.getenv("OPENAI_API_KEY") ################################### # [api자료]에서 주어진 함수 (수정 금지)import os import openai import gradio as gr from openpyxl import load_workbook from io import BytesIO import tempfile ################################### # (필수) OpenAI API 클라이언트 설정 ################################### # 공백/개행이 있으면 strip() 처리 openai.api_key = os.getenv("OPENAI_API_KEY").strip() ################################### # [api자료]에서 주어진 함수 (수정 금지) ################################### def call_api(content, system_message, max_tokens, temperature, top_p): response = openai.ChatCompletion.create( model="gpt-4o-mini", # gpt-4o-mini 모델 사용 messages=[ {"role": "system", "content": system_message}, {"role": "user", "content": content}, ], max_tokens=max_tokens, temperature=temperature, top_p=top_p, ) return response.choices[0].message['content'] ################################### # (1) 재무 분석 함수 ################################### def analyze_financials( avg_monthly_sales, # 월평균매출액 rent, # 임차료 labor_cost, # 인건비 management_cost, # 관리비 utilities, # 수도광열비 current_interest, # 지금이자 other_cost, # 기타비용 cost_ratio # 원가율 (출력에는 포함 안 함) ): """ 사용자가 입력한 8가지 항목(월평균매출액, 임차료, 인건비, 관리비, 수도광열비, 지금이자, 기타비용, 원가율)을 바탕으로 감가상각비, 순이익율, 월순수익, 손익분기점을 계산(또는 추정)하여, 각 항목별 '제목: 수치' 형태로만 반환하는 함수 (출력에서 원가율은 제외) """ system_message = ( "당신은 세무사(회계사)입니다. 아래 입력값을 바탕으로 계산한 감가상각비, 순이익율, " "월순수익, 손익분기점을 '제목: 수치' 형식으로만 알려주세요. " "추가 설명이나 문장 없이, 항목명과 수치만 반환해주세요." ) content = f""" 입력된 데이터: - 월평균매출액: {avg_monthly_sales} - 임차료: {rent} - 인건비: {labor_cost} - 관리비: {management_cost} - 수도광열비: {utilities} - 지금이자: {current_interest} - 기타비용: {other_cost} - 원가율: {cost_ratio} 다음 항목의 결과를 '제목: 수치' 형태로만 반환해 주세요: 1) 감가상각비 2) 순이익율 3) 월순수익 4) 손익분기점 """ return call_api( content=content, system_message=system_message, max_tokens=1024, temperature=0.7, top_p=1.0 ) ################################### # (2) SWOT 분석 함수 ################################### def analyze_swot(strengths, weaknesses, opportunities, threats): """ 사용자가 입력한 강점, 약점, 기회, 위협에 대해 gpt-4o-mini 모델을 활용해 분석 결과를 반환하는 함수 """ system_message = ( "당신은 swot 분석 전문가입니다. 사용자의 강점, 약점, 기회, 위협에 대해 " "검색한 내용을 요약하여 제공합니다." ) content = f""" 강점: {strengths} 약점: {weaknesses} 기회: {opportunities} 위협: {threats} """ return call_api( content=content, system_message=system_message, max_tokens=1024, temperature=0.7, top_p=1.0 ) ################################### # (3) 상권 분석 함수 (6줄 이내) ################################### def analyze_market(region, industry): """ 지역, 업종을 입력받아 1km 이내 상권분석을 '사진 언급'과 함께, 6줄 이내 텍스트로 요약해 주는 함수 """ system_message = ( "당신은 상권분석 전문가입니다. 입력된 지역과 업종에 대해 1km 이내 상권을 분석해 주세요. " "사진(또는 시각자료)에 대한 언급 포함, 응답은 6줄 이내로 제한하세요." ) content = f""" 지역: {region} 업종: {industry} """ return call_api( content=content, system_message=system_message, max_tokens=300, # 답변 길이 제한 temperature=0.7, top_p=1.0 ) ################################### # (4) 애로사항 & 컨설팅목표 분석 함수 ################################### def analyze_texts(difficulties, goals): """ 사용자 입력(애로사항, 컨설팅목표)을 gpt-4o-mini로 분석 후 결과(미리보기)를 리턴 """ # 애로사항 분석 preview_difficulties = call_api( content=difficulties, system_message="사용자가 입력한 애로사항을 간단히 분석 및 해결방안 제시해줘.", max_tokens=50, temperature=0.7, top_p=0.9 ) # 컨설팅 목표 분석 preview_goals = call_api( content=goals, system_message="사용자가 입력한 컨설팅 목표에 대한 요약 및 실행방안을 제시해줘.", max_tokens=50, temperature=0.7, top_p=0.9 ) return preview_difficulties, preview_goals ################################### # 엑셀 생성(다운로드) 함수 ################################### def generate_excel(preview_difficulties, preview_goals): """ 1) 'suu.xlsx'를 불러와서 2) A4 = 애로사항 분석 결과 A5 = 컨설팅 목표 분석 결과 3) NamedTemporaryFile로 저장 후 해당 파일 경로 반환 """ wb = load_workbook("suu.xlsx") ws = wb.active # A4, A5 셀에 결과 기입 ws["A4"] = preview_difficulties ws["A5"] = preview_goals # 메모리 버퍼에 저장 후 임시파일로 생성 output = BytesIO() wb.save(output) output.seek(0) with tempfile.NamedTemporaryFile(delete=False, suffix=".xlsx") as tmp: tmp.write(output.getvalue()) tmp_path = tmp.name return tmp_path ################################### # Gradio 이벤트 함수들 (애로사항 & 목표) ################################### def run_analyze(difficulties, goals): """ '분석하기' 버튼 누르면 실행: - gpt-4o-mini API로 분석 후 미리보기 텍스트를 반환 """ preview_difficulties, preview_goals = analyze_texts(difficulties, goals) return preview_difficulties, preview_goals def run_generate_excel(difficulties, goals, preview_difficulties, preview_goals): """ '엑셀로 다운로드' 버튼 누르면 실행: - generate_excel()로 엑셀 파일을 만들고, - Gradio File 컴포넌트로 다운로드 """ excel_path = generate_excel(preview_difficulties, preview_goals) return excel_path ################################### # Gradio 앱 구성 (4개 탭) ################################### def create_app(): with gr.Blocks() as demo: gr.Markdown("## 통합 Demo") with gr.Tabs(): # ========== 탭1: 재무 분석 ========== with gr.Tab("재무 분석"): gr.Markdown("### (입력에 원가율 포함, 결과에서 원가율 제외)") avg_monthly_sales_input = gr.Textbox(label="월평균매출액") rent_input = gr.Textbox(label="임차료") labor_cost_input = gr.Textbox(label="인건비") management_cost_input = gr.Textbox(label="관리비") utilities_input = gr.Textbox(label="수도광열비") current_interest_input = gr.Textbox(label="지금이자") other_cost_input = gr.Textbox(label="기타비용") cost_ratio_input = gr.Textbox(label="원가율") result_output_fin = gr.Textbox(label="결과(제목: 수치)") analyze_button_fin = gr.Button("계산하기") analyze_button_fin.click( fn=analyze_financials, inputs=[ avg_monthly_sales_input, rent_input, labor_cost_input, management_cost_input, utilities_input, current_interest_input, other_cost_input, cost_ratio_input ], outputs=result_output_fin ) # ========== 탭2: SWOT 분석 ========== with gr.Tab("SWOT 분석"): gr.Markdown("### (강점, 약점, 기회, 위협)") strengths_input = gr.Textbox(label="강점") weaknesses_input = gr.Textbox(label="약점") opportunities_input = gr.Textbox(label="기회") threats_input = gr.Textbox(label="위협") result_output_swot = gr.Textbox(label="검색 결과") analyze_button_swot = gr.Button("분석하기") analyze_button_swot.click( fn=analyze_swot, inputs=[strengths_input, weaknesses_input, opportunities_input, threats_input], outputs=result_output_swot ) # ========== 탭3: 상권 분석 ========== with gr.Tab("상권 분석"): gr.Markdown("### (지역 + 업종 → 1km 이내 상권분석, 6줄 이내)") region_input = gr.Textbox(label="지역") industry_input = gr.Textbox(label="업종") result_output_market = gr.Textbox(label="상권분석 결과 (최대 6줄)") analyze_button_market = gr.Button("분석하기") analyze_button_market.click( fn=analyze_market, inputs=[region_input, industry_input], outputs=result_output_market ) # ========== 탭4: 애로사항 & 목표 분석 + Excel ========== with gr.Tab("애로사항 & 목표"): gr.Markdown("### (애로사항 및 컨설팅 목표 입력 -> gpt-4o-mini 분석 -> Excel 다운로드)") with gr.Row(): difficulties_input = gr.Textbox(label="애로사항 입력", lines=3, value="") goals_input = gr.Textbox(label="컨설팅 목표 입력", lines=3, value="") analyze_button = gr.Button("분석하기") preview_difficulties_output = gr.Textbox(label="애로사항 분석 결과 미리보기", lines=3) preview_goals_output = gr.Textbox(label="컨설팅 목표 분석 결과 미리보기", lines=3) download_button = gr.Button("엑셀로 다운로드") download_file = gr.File(label="다운로드(클릭 후 저장)") # 분석 버튼 클릭 -> 미리보기 analyze_button.click( fn=run_analyze, inputs=[difficulties_input, goals_input], outputs=[preview_difficulties_output, preview_goals_output] ) # 다운로드 버튼 클릭 -> Excel 생성 download_button.click( fn=run_generate_excel, inputs=[difficulties_input, goals_input, preview_difficulties_output, preview_goals_output], outputs=[download_file] ) demo.launch() return demo ################################### # 실행 ################################### if __name__ == "__main__": app = create_app() app.launch() ################################### def call_api(content, system_message, max_tokens, temperature, top_p): response = openai.ChatCompletion.create( model="gpt-4o-mini", # 또는 다른 모델 ID 사용 messages=[ {"role": "system", "content": system_message}, {"role": "user", "content": content}, ], max_tokens=max_tokens, temperature=temperature, top_p=top_p, ) return response.choices[0].message['content'] ################################### # 분석 함수 ################################### def analyze_financials( avg_monthly_sales, # 월평균매출액 rent, # 임차료 labor_cost, # 인건비 management_cost, # 관리비 utilities, # 수도광열비 current_interest, # 지금이자 other_cost # 기타비용 ): """ 7가지 항목을 입력받아 감가상각비, 원가율, 순이익율, 월순수익, 손익분기점을 '제목: 수치' 형태로 5줄만 반환하는 함수. """ system_message = ( "당신은 재무분석가입니다. 아래 입력값을 바탕으로 " "감가상각비, 원가율, 순이익율, 월순수익, 손익분기점을 " "'제목: 수치' 형태로 5줄만 알려주세요. 추가 설명 없이 간결하게 답변해주세요." ) content = f""" 월평균매출액: {avg_monthly_sales} 임차료: {rent} 인건비: {labor_cost} 관리비: {management_cost} 수도광열비: {utilities} 지금이자: {current_interest} 기타비용: {other_cost} """ return call_api( content=content, system_message=system_message, max_tokens=500, temperature=0.7, top_p=1.0 ) ################################### # Gradio UI ################################### def create_app(): with gr.Blocks() as demo: gr.Markdown("## 재무 분석 (7개 입력) -> 감가상각비 / 원가율 / 순이익율 / 월순수익 / 손익분기점 계산") avg_monthly_sales_input = gr.Textbox(label="월평균매출액") rent_input = gr.Textbox(label="임차료") labor_cost_input = gr.Textbox(label="인건비") management_cost_input = gr.Textbox(label="관리비") utilities_input = gr.Textbox(label="수도광열비") current_interest_input = gr.Textbox(label="지금이자") other_cost_input = gr.Textbox(label="기타비용") result_output = gr.Textbox(label="결과 (제목: 수치)") analyze_button = gr.Button("계산하기") analyze_button.click( fn=analyze_financials, inputs=[ avg_monthly_sales_input, rent_input, labor_cost_input, management_cost_input, utilities_input, current_interest_input, other_cost_input ], outputs=result_output ) demo.launch() if __name__ == "__main__": app = create_app() app.launch()