zenityx commited on
Commit
552eaff
·
verified ·
1 Parent(s): 7e87ec8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +84 -112
app.py CHANGED
@@ -1,172 +1,144 @@
1
  # app.py
2
 
 
 
 
3
  import gradio as gr
4
  from transformers import pipeline
5
 
6
- # ---------------------------------------------------------
7
- # 1. Setup: Load a text2text-generation model from Hugging Face
8
- # (You can choose another model if you prefer.)
9
- # ---------------------------------------------------------
10
  prompt_analyzer = pipeline("text2text-generation", model="google/flan-t5-base")
11
 
12
- # ---------------------------------------------------------
13
- # 2. Define a function to analyze the user’s prompt
14
- # - Returns a score (1–10)
15
- # - Provides feedback on clarity/creativity/completeness
16
- # - Suggests 3 improved versions of the prompt
17
- # ---------------------------------------------------------
18
  def analyze_prompt(user_prompt: str):
19
  """
20
- Uses a text-to-text model to rate the prompt, provide feedback,
21
- and generate three improved prompt suggestions.
22
-
23
- Parameters:
24
- user_prompt (str): The user's original image-generation prompt.
25
-
26
- Returns:
27
- (str, str, str): A tuple containing:
28
- 1) Score (as text, 1–10),
29
- 2) Feedback (as a longer text),
30
- 3) Three improved prompt suggestions (as a single multiline string).
31
  """
32
 
33
  if not user_prompt.strip():
34
- return "N/A", "Please enter a valid prompt.", "No suggestions available."
35
 
36
- # Prepare an instruction to guide the model
37
- # The model output will contain rating, feedback, and 3 improvements.
38
  instruction = f"""
39
- You are an expert prompt engineer. Analyze the following prompt for an AI image generation model.
 
40
 
41
- Prompt: {user_prompt}
42
 
43
- 1. Rate the prompt on a scale of 1 to 10 based on clarity, creativity, and completeness.
44
- 2. Provide a short explanation (feedback) for your rating.
45
- 3. Give three improved versions of the prompt to make it more descriptive or more creative.
46
 
47
- Format your response in the following structure:
48
 
49
- Rating: X
50
- Feedback: <your feedback here>
51
- Improvements:
52
- 1. <improvement 1>
53
- 2. <improvement 2>
54
- 3. <improvement 3>
55
  """
 
 
 
56
 
57
- # Generate model output
58
- model_response = prompt_analyzer(instruction, max_length=200)[0]['generated_text']
59
-
60
- # Parse the output (very basic parsing logic for demonstration)
61
- # We'll look for specific keywords: "Rating:", "Feedback:", "Improvements:"
62
- rating = "N/A"
63
- feedback = ""
64
- suggestions = ""
65
-
66
- # Basic approach to splitting the text
67
- for line in model_response.split("\n"):
68
- line = line.strip()
69
- if line.lower().startswith("rating:"):
70
- rating = line.split(":", 1)[1].strip()
71
- elif line.lower().startswith("feedback:"):
72
- feedback = line.split(":", 1)[1].strip()
73
- elif line.lower().startswith("1.") or line.lower().startswith("- 1."):
74
- # Start collecting improvements
75
- suggestions += line + "\n"
76
- elif line.lower().startswith("2.") or line.lower().startswith("- 2."):
77
- suggestions += line + "\n"
78
- elif line.lower().startswith("3.") or line.lower().startswith("- 3."):
79
- suggestions += line + "\n"
80
- elif line.lower().startswith("improvements:"):
81
- # If the model has a separate "Improvements:" heading
82
- suggestions += "\n"
83
-
84
- # If the model didn't output lines with numbering, just set a fallback
85
- if not suggestions.strip():
86
- # We might handle the entire text as suggestions or produce a fallback
87
- suggestions = "Could not parse suggestions properly.\n" + model_response
88
 
89
  return rating, feedback, suggestions
90
 
91
- # ---------------------------------------------------------
92
- # 3. Define some example prompts for reference
93
- # ---------------------------------------------------------
94
  example_prompts = [
95
  "A majestic dragon soaring above a medieval castle, fantasy art style, highly detailed",
96
  "A peaceful countryside landscape with rolling hills and a small cottage at sunset",
97
  "A cyberpunk city scene with neon lights, flying cars, and towering skyscrapers",
98
  ]
99
 
100
- # ---------------------------------------------------------
101
- # 4. Build the Gradio interface
102
- # ---------------------------------------------------------
103
  def set_example_prompt(example):
104
- """
105
- Utility function to load an example prompt into the text input box.
106
- """
107
  return example
108
 
 
109
  with gr.Blocks() as demo:
110
- gr.Markdown(
111
- """
112
- # Interactive Prompt Engineering App
113
- **Learn how to craft better prompts for AI image generation.**
114
-
115
- 1. Enter your prompt below.
116
- 2. Click "Evaluate Prompt" to get a **score**, **feedback**, and **3 improved prompts**.
117
- 3. Use the dropdown to load example prompts for inspiration.
118
- """
119
- )
120
-
121
  with gr.Row():
122
  with gr.Column():
123
- # Dropdown to select an example
124
  example_dropdown = gr.Dropdown(
125
- label="Choose an example prompt to load",
126
  choices=example_prompts,
127
  value=None,
128
  interactive=True
129
  )
130
-
131
- # Textbox for user prompt input
132
  user_prompt_input = gr.Textbox(
133
- label="Enter your prompt here:",
134
  lines=4,
135
- placeholder="E.g. 'A futuristic cityscape with neon lights at night, highly detailed...'"
136
  )
137
-
138
- # Button to set example prompt in the textbox
139
  load_example_btn = gr.Button("Load Example Prompt")
140
-
141
- # Button to analyze the user's prompt
142
  analyze_btn = gr.Button("Evaluate Prompt")
143
-
144
  with gr.Column():
145
  score_output = gr.Textbox(
146
- label="Prompt Quality Score (1-10)",
147
  interactive=False
148
  )
149
  feedback_output = gr.Textbox(
150
- label="Feedback",
151
  lines=3,
152
  interactive=False
153
  )
154
  suggestions_output = gr.Textbox(
155
- label="Improved Prompt Suggestions",
156
  lines=6,
157
  interactive=False
158
  )
159
 
160
- # Define the interactions
161
- load_example_btn.click(fn=set_example_prompt,
162
- inputs=[example_dropdown],
163
- outputs=[user_prompt_input])
164
-
165
- analyze_btn.click(fn=analyze_prompt,
166
- inputs=[user_prompt_input],
167
- outputs=[score_output, feedback_output, suggestions_output])
 
 
 
168
 
169
- # ---------------------------------------------------------
170
- # 5. Launch the Gradio app
171
- # ---------------------------------------------------------
172
  demo.launch()
 
1
  # app.py
2
 
3
+ #!pip install gradio transformers # <--- เอาออกได้หากใช้ requirements.txt
4
+
5
+ import re
6
  import gradio as gr
7
  from transformers import pipeline
8
 
9
+ # โหลดโมเดลจาก Hugging Face (เลือกได้ตามต้องการ)
 
 
 
10
  prompt_analyzer = pipeline("text2text-generation", model="google/flan-t5-base")
11
 
 
 
 
 
 
 
12
  def analyze_prompt(user_prompt: str):
13
  """
14
+ ฟังก์ชันนี้จะ:
15
+ 1. ตรวจสอบความว่างเปล่าของ Prompt
16
+ 2. ส่ง Prompt เข้าโมเดล text2text-generation เพื่อขอ:
17
+ - Rating (1–10)
18
+ - Feedback (เหตุผลหรือคำแนะนำ)
19
+ - Improvements (ตัวอย่าง Prompt ที่ปรับปรุงแล้ว)
20
+ 3. แยกวิเคราะห์ (Parse) ข้อความที่โมเดลตอบมา ด้วย Regex
21
+ 4. คืนค่าผลลัพธ์เป็น (rating, feedback, suggestions)
 
 
 
22
  """
23
 
24
  if not user_prompt.strip():
25
+ return "N/A", "กรุณากรอก Prompt ที่ถูกต้อง", "ไม่มีคำแนะนำ"
26
 
 
 
27
  instruction = f"""
28
+ คุณคือนักออกแบบ Prompt มืออาชีพ
29
+ โปรดวิเคราะห์ Prompt ด้านล่างสำหรับการสร้างภาพด้วย AI
30
 
31
+ Prompt: {user_prompt}
32
 
33
+ 1. ให้คะแนน (Rating) Prompt นี้แบบเต็ม 10 คะแนน
34
+ 2. อธิบายสั้น ว่าทำไมถึงได้คะแนนนี้ (Feedback)
35
+ 3. เขียน Prompt ที่ปรับปรุงให้ดีขึ้น (Improvements) อย่างน้อย 3 รูปแบบ
36
 
37
+ กรุณาเรียบเรียงผลลัพธ์ตามโครงสร้าง:
38
 
39
+ Rating: X
40
+ Feedback: (อธิบาย)
41
+ Improvements:
42
+ 1. ...
43
+ 2. ...
44
+ 3. ...
45
  """
46
+
47
+ # เรียกใช้งานโมเดล
48
+ model_response = prompt_analyzer(instruction, max_length=300)[0]["generated_text"]
49
 
50
+ # ใช้ Regex เพื่อค้นหา Rating, Feedback และ Improvements
51
+ # โดยสมมติว่าตัวโมเดลจะมีคำว่า "Rating:", "Feedback:", และ "Improvements:" อยู่จริง
52
+ rating_pattern = r"Rating:\s*(\d+)"
53
+ feedback_pattern = r"Feedback:\s*(.*?)(?=Improvements:|$)"
54
+ improvements_pattern = r"Improvements:\s*(.*)"
55
+
56
+ rating_match = re.search(rating_pattern, model_response)
57
+ feedback_match = re.search(feedback_pattern, model_response, re.DOTALL)
58
+ improvements_match = re.search(improvements_pattern, model_response, re.DOTALL)
59
+
60
+ if rating_match:
61
+ rating = rating_match.group(1).strip()
62
+ else:
63
+ rating = "N/A"
64
+
65
+ if feedback_match:
66
+ feedback = feedback_match.group(1).strip()
67
+ else:
68
+ feedback = "ไม่พบคำแนะนำ"
69
+
70
+ if improvements_match:
71
+ suggestions = improvements_match.group(1).strip()
72
+ else:
73
+ suggestions = "ไม่พบคำแนะนำ"
 
 
 
 
 
 
 
74
 
75
  return rating, feedback, suggestions
76
 
77
+ # ตัวอย่าง Prompt ที่มีไว้ให้ผู้ใช้เลือก (Dropdown)
 
 
78
  example_prompts = [
79
  "A majestic dragon soaring above a medieval castle, fantasy art style, highly detailed",
80
  "A peaceful countryside landscape with rolling hills and a small cottage at sunset",
81
  "A cyberpunk city scene with neon lights, flying cars, and towering skyscrapers",
82
  ]
83
 
84
+ # ฟังก์ชันสำหรับโหลด Prompt ตัวอย่าง
 
 
85
  def set_example_prompt(example):
 
 
 
86
  return example
87
 
88
+ # สร้าง Gradio Interface
89
  with gr.Blocks() as demo:
90
+ gr.Markdown("""
91
+ # แอปพลิเคชันเรียนรู้ Prompt Engineering แบบโต้ตอบ
92
+ **(โดย สถาบัน Prompt Engineers Academy)**
93
+
94
+ 1. พิมพ์ Prompt ของคุณในช่องด้านล่าง
95
+ 2. คลิก "Evaluate Prompt" เพื่อรับคะแนน (Rating), ข้อเสนอแนะ (Feedback) และตัวอย่าง Prompt ที่ปรับปรุงแล้ว (Improvements)
96
+ 3. เลือก Prompt จากตัวอย่าง (Dropdown) เพื่อศึกษาเพิ่มเติมได้
97
+ """)
98
+
 
 
99
  with gr.Row():
100
  with gr.Column():
 
101
  example_dropdown = gr.Dropdown(
102
+ label="ตัวอย่าง Prompt ที่มีให้",
103
  choices=example_prompts,
104
  value=None,
105
  interactive=True
106
  )
 
 
107
  user_prompt_input = gr.Textbox(
108
+ label="ใส่ Prompt ของคุณ:",
109
  lines=4,
110
+ placeholder="เช่น 'A futuristic cityscape with neon lights at night, highly detailed...'"
111
  )
 
 
112
  load_example_btn = gr.Button("Load Example Prompt")
 
 
113
  analyze_btn = gr.Button("Evaluate Prompt")
114
+
115
  with gr.Column():
116
  score_output = gr.Textbox(
117
+ label="คะแนน (Rating)",
118
  interactive=False
119
  )
120
  feedback_output = gr.Textbox(
121
+ label="คำแนะนำ (Feedback)",
122
  lines=3,
123
  interactive=False
124
  )
125
  suggestions_output = gr.Textbox(
126
+ label="Prompt ที่ปรับปรุงแล้ว (Improvements)",
127
  lines=6,
128
  interactive=False
129
  )
130
 
131
+ load_example_btn.click(
132
+ fn=set_example_prompt,
133
+ inputs=[example_dropdown],
134
+ outputs=[user_prompt_input]
135
+ )
136
+
137
+ analyze_btn.click(
138
+ fn=analyze_prompt,
139
+ inputs=[user_prompt_input],
140
+ outputs=[score_output, feedback_output, suggestions_output]
141
+ )
142
 
143
+ # เปิดใช้งานแอป Gradio
 
 
144
  demo.launch()