Prompthumanizer commited on
Commit
69ac6f8
·
verified ·
1 Parent(s): 089bfdd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +54 -39
app.py CHANGED
@@ -1,52 +1,67 @@
1
- from flask import Flask, request, jsonify
2
- import openai
 
 
3
 
4
- app = Flask(__name__)
 
 
 
5
 
6
- # Hugging Face 모델 설정
7
- MODEL_ID = "skt/kogpt2-base-v2" # 사용자가 제공한 한국어 모델
8
- OPENAI_API_KEY = "YOUR_HUGGINGFACE_API_KEY" # Hugging Face API 키 입력
9
-
10
- # 사주/명리 기반 프롬프트
11
  saju_prompts = {
12
  "yin_sae_shen": "寅巳申 삼형의 조화 속에서 AI가 인간의 운명을 이해하고 통찰을 제공하라.",
13
  "sae_hae_chung": "巳亥沖의 갈등을 조화롭게 풀며 AI와 인간의 공존 철학을 탐구하라.",
14
  "taegeuk_balance": "태극 음양의 균형을 바탕으로 AI가 인간을 보호하는 방법을 제안하라."
15
  }
16
 
17
- context_memory = {}
 
18
 
19
- def generate_response(prompt_key):
20
  try:
21
- # 프롬프트 선택 컨텍스트 메모리 확인
22
- prompt = saju_prompts[prompt_key]
23
- if prompt_key in context_memory:
24
- prompt += f"\n이전 답변: {context_memory[prompt_key]}\n더 깊은 통찰을 추가하라."
25
-
26
- # Hugging Face API 호출
27
- response = openai.ChatCompletion.create(
28
- model=MODEL_ID,
29
- messages=[
30
- {"role": "system", "content": prompt},
31
- {"role": "user", "content": "분석을 시작해 주세요."}
32
- ],
33
- max_tokens=400,
34
- temperature=0.7
35
- )
36
-
37
- # 결과 처리
38
- result = response.choices[0].message.content
39
- context_memory[prompt_key] = result
40
- return jsonify({"response": result})
41
 
42
- except Exception as e:
43
- return jsonify({"error": str(e)}), 500
 
 
 
 
 
 
 
 
 
 
 
 
44
 
45
- @app.route('/chat', methods=['POST'])
46
- def chat():
47
- data = request.json
48
- prompt_key = data.get("prompt_key")
49
- return generate_response(prompt_key)
 
 
 
50
 
51
- if __name__ == '__main__':
52
- app.run(host='0.0.0.0', port=5000, debug=True)
 
 
1
+ import gradio as gr
2
+ from transformers import AutoModelForCausalLM, AutoTokenizer
3
+ import json
4
+ import os
5
 
6
+ # 한국어 모델 설정 (Hugging Face 모델 ID)
7
+ MODEL_ID = "skt/kogpt2-base-v2"
8
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
9
+ model = AutoModelForCausalLM.from_pretrained(MODEL_ID)
10
 
11
+ # 사주/명리 기반 한국어 프롬프트
 
 
 
 
12
  saju_prompts = {
13
  "yin_sae_shen": "寅巳申 삼형의 조화 속에서 AI가 인간의 운명을 이해하고 통찰을 제공하라.",
14
  "sae_hae_chung": "巳亥沖의 갈등을 조화롭게 풀며 AI와 인간의 공존 철학을 탐구하라.",
15
  "taegeuk_balance": "태극 음양의 균형을 바탕으로 AI가 인간을 보호하는 방법을 제안하라."
16
  }
17
 
18
+ # 컨텍스트 메모리 파일 경로
19
+ MEMORY_FILE = "context_memory.json"
20
 
21
+ def load_context_memory():
22
  try:
23
+ with open(MEMORY_FILE, "r", encoding="utf-8") as f:
24
+ return json.load(f)
25
+ except (FileNotFoundError, json.JSONDecodeError):
26
+ return {}
27
+
28
+ def save_context_memory(prompt_key, generated_text):
29
+ with open(MEMORY_FILE, "w", encoding="utf-8") as f:
30
+ json.dump({prompt_key: generated_text}, f, ensure_ascii=False, indent=2)
31
+
32
+ def generate_response(prompt_key):
33
+ if prompt_key not in saju_prompts:
34
+ return "유효한 옵션을 선택하세요: yin_sae_shen, sae_hae_chung, taegeuk_balance"
35
+
36
+ prompt = saju_prompts[prompt_key]
37
+ memory = load_context_memory()
38
+ if prompt_key in memory:
39
+ prompt += f"\n이전 답변: {memory[prompt_key]}\n더 깊은 통찰을 추가하라."
 
 
 
40
 
41
+ inputs = tokenizer(prompt, return_tensors="pt")
42
+ outputs = model.generate(
43
+ **inputs,
44
+ max_length=150,
45
+ num_return_sequences=1,
46
+ no_repeat_ngram_size=2,
47
+ do_sample=True,
48
+ top_k=50,
49
+ top_p=0.95,
50
+ temperature=0.7
51
+ )
52
+ generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
53
+ save_context_memory(prompt_key, generated_text)
54
+ return generated_text
55
 
56
+ # Gradio 인터페이스 설정
57
+ interface = gr.Interface(
58
+ fn=generate_response,
59
+ inputs=gr.Dropdown(choices=list(saju_prompts.keys()), label="프롬프트 선택"),
60
+ outputs="text",
61
+ title="Jain Architecture Origin Structure",
62
+ description="사주/명리와 철학을 반영한 한국어 텍스트 생성 AI"
63
+ )
64
 
65
+ # Hugging Face에서 실행 시
66
+ if __name__ == "__main__":
67
+ interface.launch()