dynapricing / app.py
fudii0921's picture
Update app.py
6b1c0bc verified
import gradio as gr
import numpy as np
import requests
import cohere
from dotenv import load_dotenv
import os
from gradio_pdf import PDF
load_dotenv(verbose=True)
coherekey = os.environ.get("COHERE_API_KEY")
co = cohere.ClientV2(api_key=coherekey)
cresponse = requests.get("https://www.ryhintl.com/chatgpt/dynamic.php")
cohere_doc = cresponse.json()
setsumei = '''
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>需要と供給の均衡点</title>
<style>
body {
font-family: Arial, sans-serif;
line-height: 1.6;
margin: 20px;
}
h1, h2 {
color: #2c3e50;
}
p {
margin-bottom: 10px;
}
ul {
margin-bottom: 20px;
}
.highlight {
background-color: #f9f9f9;
border-left: 5px solid #3498db;
padding: 10px;
margin-bottom: 20px;
}
</style>
</head>
<body>
<h1>需要と供給の均衡点</h1>
<p>最も基本的な方法は、需要曲線と供給曲線の交点を見つけることです。この交点が市場の均衡価格を示します。</p>
<div class="highlight">
<p>需要曲線 = Qd = a - bP</p>
<p>供給曲線 = Qs = c + dP</p>
</div>
<p>ここで、P は価格、a, b, c, d は定数です。均衡点では Qd = Qs となるため、次の方程式を解きます:</p>
<div class="highlight">
<p>a - bP = c + dP</p>
<p>P = (a - c) / (b + d)</p>
</div>
<p>この P が均衡価格です。</p>
<h2>利潤最大化</h2>
<p>企業が利潤を最大化するための価格設定も重要です。利潤 π は次のように表されます:</p>
<div class="highlight">
<p>π = TR - TC</p>
<p>TC = FC + VC</p>
</div>
<p>ここで、TR は総収入、TC は総費用です。総収入 TR は価格 P と販売量 Q の積で表されます:</p>
<div class="highlight">
<p>TR = P ⋅ Q</p>
</div>
<p>総費用 TC は固定費用 FC と変動費用 VC の和です:</p>
<div class="highlight">
<p>TC = FC + VC</p>
</div>
<p>利潤を最大化するためには、次の条件を満たす価格 P を見つけます:</p>
<div class="highlight">
<p>dπ / dP = 0</p>
</div>
<h2>価格弾力性を考慮した価格設定</h2>
<p>価格弾力性を考慮することで、価格変更が需要に与える影響を評価できます。価格弾力性 ϵ は次のように定義されます:</p>
<div class="highlight">
<p>ϵ = (ΔQ / Q) / (ΔP / P)</p>
</div>
<p>ΔQ は需要の変化量、ΔP は価格の変化量です。価格弾力性が高い場合、価格を下げることで需要が大幅に増加し、総収入が増える可能性があります。</p>
<p>これらの方法を組み合わせることで、より精度の高い最適価格を導出することができます。具体的な状況に応じて適切な手法を選択することが重要です。</p>
<h2>価格弾力性が高い場合</h2>
<ul>
<li><strong>メリット:</strong>
<ul>
<li>価格変更の影響: 価格を下げると需要が大幅に増加するため、売上を増やすことができます。</li>
<li>競争力: 価格を柔軟に調整することで、競合他社に対して優位に立つことができます。</li>
</ul>
</li>
<li><strong>デメリット:</strong>
<ul>
<li>収益の不安定性: 価格を上げると需要が大幅に減少するため、収益が不安定になる可能性があります。</li>
<li>価格競争: 価格弾力性が高い市場では、価格競争が激化し、利益率が低下することがあります。</li>
</ul>
</li>
</ul>
<h2>価格弾力性が低い場合</h2>
<ul>
<li><strong>メリット:</strong>
<ul>
<li>収益の安定性: 価格変更が需要に与える影響が小さいため、収益が安定しやすいです。</li>
<li>価格設定の自由度: 価格を上げても需要が大きく減少しないため、利益率を維持しやすいです。</li>
</ul>
</li>
<li><strong>デメリット:</strong>
<ul>
<li>需要の増加: 価格を下げても需要が大幅に増加しないため、売上を増やすのが難しいです。</li>
<li>競争力: 価格を柔軟に調整することで競争力を高めるのが難しいです。</li>
</ul>
</li>
</ul>
<p>企業の戦略や市場の特性に応じて、価格弾力性の高低がどちらが良いかを判断することが重要です。具体的な状況に応じて、適切な価格戦略を選択することが求められます。</p>
<br /><br />
<h1>需要曲線と供給曲線の切片と傾き</h1>
<h2>1. 需要曲線の切片</h2>
<p>需要曲線の切片は、需要曲線が価格軸(縦軸)と交わる点を指します。需要曲線は通常、次のような線形方程式で表されます:</p>
<div class="highlight">
<p>Q<sub>d</sub> = a - bP</p>
</div>
<p>ここで、</p>
<ul>
<li>Q<sub>d</sub>は需要量</li>
<li>Pは価格</li>
<li>aは需要曲線の切片</li>
<li>bは価格に対する需要の変化率(傾き)</li>
</ul>
<p>切片aは、価格がゼロのときの需要量を示します。つまり、価格がゼロの場合に消費者が購入する量です。この値は、需要曲線が価格軸と交わる点の需要量を表します。</p>
<p>例えば、需要曲線がQ<sub>d</sub> = 50 − 2Pである場合、切片aは50です。これは、価格がゼロのときに需要量が50であることを意味します。</p>
<p>需要曲線の切片は、消費者の基本的な需要を示し、価格が変動する際の需要の変化を理解するための重要な要素です。</p>
<h2>2. 需要曲線の傾き</h2>
<p>需要曲線の傾きは、価格の変化に対する需要量の変化を示す重要な指標です。需要曲線は通常、次のような線形方程式で表されます:</p>
<div class="highlight">
<p>Q<sub>d</sub> = a - bP</p>
</div>
<p>ここで、</p>
<ul>
<li>Q<sub>d</sub>は需要量</li>
<li>Pは価格</li>
<li>aは需要曲線の切片</li>
<li>bは価格に対する需要の変化率(傾き)</li>
</ul>
<p>傾きbは、価格が1単位変化したときに需要量がどれだけ変化するかを示します。具体的には、傾きは次のように計算されます:</p>
<div class="highlight">
<p>b = ΔQ<sub>d</sub>/ΔP</p>
</div>
<p>ここで、ΔQ<sub>d</sub>は需要量の変化、ΔPは価格の変化です。</p>
<p>例えば、需要曲線がQ<sub>d</sub> = 50 - 2Pである場合、傾きbは2です。これは、価格が1単位上昇すると需要量が2単位減少することを意味します。</p>
<h2>3. 供給曲線の切片</h2>
<p>供給曲線の切片は、供給曲線が価格軸(縦軸)と交わる点を指します。供給曲線は通常、次のような線形方程式で表されます:</p>
<div class="highlight">
<p>Q<sub>s</sub> = c + dP</p>
</div>
<p>ここで、</p>
<ul>
<li>Q<sub>s</sub>は供給量</li>
<li>Pは価格</li>
<li>cは供給曲線の切片</li>
<li>dは価格に対する供給の変化率(傾き)</li>
</ul>
<p>切片cは、価格がゼロのときの供給量を示します。つまり、価格がゼロの場合に供給者が提供する量です。この値は、供給曲線が価格軸と交わる点の供給量を表します。</p>
<p>例えば、供給曲線がQ<sub>s</sub> = 10 + 3Pである場合、切片cは10です。これは、価格がゼロのときに供給量が10であることを意味します。</p>
<p>供給曲線の切片は、供給者の基本的な供給意欲を示し、価格が変動する際の供給の変化を理解するための重要な要素です。</p>
<h2>4. 供給曲線の傾き</h2>
<p>供給曲線の傾きは、価格の変化に対する供給量の変化を示す重要な指標です。供給曲線は通常、次のような線形方程式で表されます:</p>
<div class="highlight">
<p>Q<sub>s</sub> = c + dP</p>
</div>
<p>ここで、</p>
<ul>
<li>Q<sub>s</sub>は供給量</li>
<li>Pは価格</li>
<li>cは供給曲線の切片</li>
<li>dは供給曲線の傾き</li>
</ul>
<p>傾きdは、価格が1単位変化したときに供給量がどれだけ変化するかを示します。具体的には、傾きは次のように計算されます:</p>
<div class="highlight">
<p>d = ΔQ<sub>s</sub>/ΔP</p>
</div>
<p>ここで、ΔQ<sub>s</sub>は供給量の変化、ΔPは価格の変化です。</p>
<p>例えば、供給曲線がQ<sub>s</sub> = 10 + 3Pである場合、傾きdは3です。これは、価格が1単位上昇すると供給量が3単位増加することを意味します。</p>
<p>傾きが大きいほど、価格の変化に対する供給の反応が大きくなります。逆に、傾きが小さい場合、価格の変化に対する供給の反応は小さくなります。</p>
<p>供給曲線の傾きは、価格弾力性の分析や市場の動向を理解するために重要な要素です。</p>
</body>
</html>
'''
js = """
function createGradioAnimation() {
var container = document.createElement('div');
container.id = 'gradio-animation';
container.style.fontSize = '2em';
container.style.fontWeight = 'bold';
container.style.textAlign = 'center';
container.style.marginBottom = '20px';
var text = 'ダイナミック・プライシング';
for (var i = 0; i < text.length; i++) {
(function(i){
setTimeout(function(){
var letter = document.createElement('span');
var randomColor = "#" + Math.floor(Math.random() * 16777215).toString(16);
letter.style.color = randomColor;
letter.style.opacity = '0';
letter.style.transition = 'opacity 0.5s';
letter.innerText = text[i];
container.appendChild(letter);
setTimeout(function() {
letter.style.opacity = '1';
}, 50);
}, i * 250);
})(i);
}
var gradioContainer = document.querySelector('.gradio-container');
gradioContainer.insertBefore(container, gradioContainer.firstChild);
return 'Animation created';
}
"""
def process_cohere(prompt):
if prompt == "":
return "プロンプトを入力してください。", "プロンプトは必須です。"
else:
system_message = """## あなたは、LLMのスペシャリストです。"""
prompt_message = prompt+" 結果をわかりやすく要約してください。"
messages = [
{"role": "system", "content": system_message},
{"role": "user", "content": prompt_message},
]
# Step 2: Tool planning and calling
response = co.chat(
model="command-r-plus-08-2024",
messages=messages,
documents=cohere_doc
)
return response.message.content[0].text
def display_pdf(filename):
return filename
def download_pdf():
response = requests.get("https://www.ryhintl.com/dynamic-pricing.pdf")
file_path = "dynamic-pricing.pdf"
with open(file_path, "wb") as f:
f.write(response.content)
return file_path
def dyn_chart(p1,p2,p3,p4,p5):
# 需要曲線と供給曲線のパラメータ
a = p1 # 需要曲線の切片
b = p2 # 需要曲線の傾き
c = p3 # 供給曲線の切片
d = p4 # 供給曲線の傾き
# 価格の範囲
P = np.linspace(0, p5, p5)
# 需要曲線と供給曲線の計算
Q_d = a - b * P
Q_s = c + d * P
# 均衡点の計算
equilibrium_price = (a - c) / (b + d)
equilibrium_quantity = a - b * equilibrium_price
print(f"均衡価格: {equilibrium_price}")
print(f"均衡数量: {equilibrium_quantity}")
# グラフのプロット
pplot = f'''
import numpy as np<br />
import matplotlib.pyplot as plt<br />
import japanize_matplotlib<br />
<br />
# 需要曲線と供給曲線のパラメータ<br />
a = {p1} # 需要曲線の切片<br />
b = {p2} # 需要曲線の傾き<br />
c = {p3} # 供給曲線の切片<br />
d = {p4} # 供給曲線の傾き<br />
# 価格の範囲<br />
P = np.linspace(0, {p5}, {p5})<br />
# 需要曲線と供給曲線の計算<br />
Q_d = a - b * P<br />
Q_s = c + d * P<br />
# 均衡点の計算<br />
equilibrium_price = (a - c) / (b + d)<br />
equilibrium_quantity = a - b * equilibrium_price<br />
plt.figure(figsize=(10, 6))<br />
plt.plot(P, Q_d, label='需要曲線')<br />
plt.plot(P, Q_s, label='供給曲線')<br />
plt.axvline(x={equilibrium_price}, color='r', linestyle='--', label='均衡価格')<br />
plt.axhline(y={equilibrium_quantity}, color='r', linestyle='--', label='均衡数量')<br />
plt.xlabel('価格')<br />
plt.ylabel('数量')<br />
plt.title('需要と供給の均衡点')<br />
plt.legend()<br />
plt.grid(True)<br />
plt.savefig('plot.png')<br />
plt.show()'''
return pplot
def load_css():
with open('theme.css', 'r') as file:
css_content = file.read()
return css_content
# 価格弾力性を計算する関数
def calculate_price_elasticity(prices, quantities):
# 価格と需要の変化率を計算
delta_p = np.diff(prices) / prices[:-1]
delta_q = np.diff(quantities) / quantities[:-1]
# 価格弾力性を計算
elasticity = delta_q / delta_p
return elasticity
# Gradioインターフェース用の関数
def gradio_calculate_price_elasticity(prices_str, quantities_str):
# 文字列を数値の配列に変換
prices = np.array([float(p) for p in prices_str.split(',')])
quantities = np.array([float(q) for q in quantities_str.split(',')])
# 価格弾力性を計算
price_elasticity = calculate_price_elasticity(prices, quantities)
# 結果を表示
results = []
for i, e in enumerate(price_elasticity):
results.append(f"価格 {prices[i]} から {prices[i+1]} への変化に対する価格弾力性: {e}")
# 平均価格弾力性を計算
average_elasticity = np.mean(price_elasticity)
results.append(f"平均価格弾力性: {average_elasticity}")
return "\n".join(results)
# 利潤を計算する関数
def calculate_profit(price, quantity, fixed_cost, variable_cost_per_unit):
# 総収入 (TR) を計算
total_revenue = price * quantity
print("Total revenue: ",total_revenue)
# 総費用 (TC) を計算
total_cost = (fixed_cost * quantity) + (variable_cost_per_unit * quantity)
print("Total cost: ",total_cost)
# 利潤 (π) を計算
profit = total_revenue - total_cost
print("Profit: ",profit)
return profit
# Gradioインターフェース用の関数
def gradio_calculate_profit(price, quantity, fixed_cost, variable_cost_per_unit):
profit = calculate_profit(int(price), int(quantity), int(fixed_cost), int(variable_cost_per_unit))
return f"利潤 (π): {profit}"
# 価格弾力性を用いて適正な価格を計算する関数
def calculate_optimal_price(current_price, current_quantity, price_elasticity, target_quantity):
# 価格弾力性の公式を利用して新しい価格を計算
optimal_price = current_price * (1 + (target_quantity - current_quantity) / (price_elasticity * current_quantity))
return optimal_price
# Gradioインターフェース用の関数
def gradio_calculate_optimal_price(current_price, current_quantity, price_elasticity, target_quantity):
optimal_price = calculate_optimal_price(current_price, current_quantity, price_elasticity, target_quantity)
return f"適正な価格: {optimal_price}"
# Custom CSS for the Groq badge and color scheme (feel free to edit however you wish)
custom_css = """
.gradio-container {
background-color: #f5f5f5;
}
.gr-button-primary {
background-color: #f55036 !important;
border-color: #f55036 !important;
}
.gr-button-secondary {
color: #f55036 !important;
border-color: #f55036 !important;
}
#groq-badge {
position: fixed;
bottom: 20px;
right: 20px;
z-index: 1000;
}
"""
#with gr.Blocks(theme=gr.themes.Default()) as llm:
with gr.Blocks(css=load_css(),js=js,title="ダイナミック・プライシング",theme=gr.themes.Soft()) as llm:
with gr.Tab("価格弾力性"):
gr.Markdown("# 🗞️ 価格弾力性")
with gr.Row():
price_input = gr.Textbox(label="価格 (カンマ区切り)",value="100000, 120000, 140000, 160000, 180000")
demand_input = gr.Textbox(label="需要量 (カンマ区切り)",value="1000, 900, 800, 700, 600")
with gr.Row():
response_output = gr.Textbox(label="AIアシスタントの応答")
submit_button = gr.Button("価格弾力性プロセス", variant="primary")
# Add the Groq badge
gr.HTML("""
<div id="groq-badge">
<div style="color: #f55036; font-weight: bold;">POWERED BY EPRAG</div>
</div>
""")
submit_button.click(
gradio_calculate_price_elasticity,
inputs=[price_input, demand_input],
outputs=[response_output]
)
with gr.Tab("利潤"):
gr.Markdown("# 🗞️ 利潤")
with gr.Row():
price_input = gr.Number(label="価格",value="150000")
quantity_input = gr.Number(label="販売量",value="150")
fixed_input = gr.Number(label="固定費用",value="80000")
var_unit = gr.Number(label="単位あたりの変動費用",value="1000")
with gr.Row():
dynamic_output = gr.Textbox(label="AIアシスタントの応答")
submit_button = gr.Button("利潤プロセス", variant="primary")
submit_button.click(
gradio_calculate_profit,
inputs=[price_input,quantity_input,fixed_input,var_unit],
outputs=[dynamic_output]
)
# Add the Groq badge
gr.HTML("""
<div id="groq-badge">
<div style="color: #f55036; font-weight: bold;">POWERED BY EPRAG</div>
</div>
""")
with gr.Tab("適正価格"):
gr.Markdown("# 🗞️ 適正価格")
with gr.Row():
current_price_input = gr.Number(label="現在の価格",value=150000)
current_demand_input = gr.Number(label="現在の需要量",value=1000)
elasticity_input = gr.Number(label="価格弾力性",value=-1.5)
target_demand_input = gr.Number(label="目標とする需要量",value=1200)
with gr.Row():
price_output = gr.Textbox(label="AIアシスタントの応答")
submit_button = gr.Button("適正価格プロセス", variant="primary")
submit_button.click(
gradio_calculate_optimal_price,
inputs=[current_price_input,current_demand_input,elasticity_input,target_demand_input],
outputs=[price_output]
)
# Add the Groq badge
gr.HTML("""
<div id="groq-badge">
<div style="color: #f55036; font-weight: bold;">POWERED BY EPRAG</div>
</div>
""")
with gr.Tab("ダイナミック・プライシング"):
gr.Markdown("# 🗞️ ダイナミック・プライシング")
with gr.Row():
#logout_output = gr.Textbox(label="AIアシスタントの応答")
dyn_input1 = gr.Number(label="需要曲線の切片",value=100)
dyn_input2 = gr.Number(label="需要曲線の傾き",value=2)
dyn_input3 = gr.Number(label="供給曲線の切片",value=20)
dyn_input4 = gr.Number(label="供給曲線の傾き",value=1)
dyn_input5 = gr.Number(label="価格の範囲",value=10000)
logout_output = gr.HTML(label="AIアシスタントの応答")
submit_button = gr.Button("ダイナミック・プライシング", variant="primary")
submit_button.click(
dyn_chart,
inputs=[dyn_input1,dyn_input2,dyn_input3,dyn_input4,dyn_input5],
outputs=[logout_output]
)
gr.Markdown("""
## 使い方:
上記のPythonコードをコピーして、ファイル保存して実行してください。
""")
# Add the Groq badge
gr.HTML("""
<div id="groq-badge">
<div style="color: #f55036; font-weight: bold;">POWERED BY EPRAG</div>
</div>
""")
with gr.Tab("RAG"):
gr.Markdown("# 🗞️ RAG")
with gr.Row():
rag_input = gr.Textbox(label="プロンプト",value="最適価格導出のアプローチについて詳しく教えてください。")
with gr.Row():
rag_output = gr.Textbox(label="AIアシスタントの応答")
submit_button = gr.Button("RAGプロセス", variant="primary")
submit_button.click(
process_cohere,
inputs=[rag_input],
outputs=[rag_output]
)
# Add the Groq badge
gr.HTML("""
<div id="groq-badge">
<div style="color: #f55036; font-weight: bold;">POWERED BY EPRAG</div>
</div>
""")
with gr.Tab("解説"):
gr.Markdown("# 📄 解説")
with gr.Row():
#logout_output = gr.Textbox(label="AIアシスタントの応答")
gr.HTML(label="解説",value=setsumei)
with gr.Tab("資料"):
gr.Markdown("# 📄 資料")
with gr.Row():
if os.path.exists("./dynamic-pricing.pdf"):
pdf_output = PDF(label="資料",value="./dynamic-pricing.pdf")
else:
download_pdf()
pdf_output = PDF(label="資料",value="./dynamic-pricing.pdf")
#pdf = PDF(label="Upload PDF",visible=False)
#pdf_output = gr.File(visible=False)
#pdf_output = PDF(label="資料",value="./dynamic-pricing.pdf")
#pdf.upload(display_pdf, inputs=pdf, outputs=pdf_output)
llm.launch(share=True,pwa=True,favicon_path="favicon.ico")