Natnichamm748 commited on
Commit
6036e92
·
verified ·
1 Parent(s): ce70b45

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +26 -36
app.py CHANGED
@@ -1,46 +1,36 @@
1
  import gradio as gr
2
- from PIL import Image
3
- from transformers import Pix2StructProcessor, Pix2StructForConditionalGeneration
4
 
5
- # 1. โหลดโมเดล (ทำพียงคเดียวเมื่อแอปพลิเคชันเิ่มทำง)
6
- model_name = "google/pix2struct-docvqa-base"
7
- processor = Pix2StructProcessor.from_pretrained(model_name)
8
- model = Pix2StructForConditionalGeneration.from_pretrained(model_name)
9
 
10
- # 2. กำหนดฟังก์ชันสำหรับ Gradio
11
- def answer_question_on_image(uploaded_image, question):
12
- if uploaded_image is None or not question:
13
- return "Please upload an image and ask a question."
14
-
15
- try:
16
- # แปลง input รูปภาพของ Gradio (ซึ่งเป็น PIL Image)
17
- image = uploaded_image.convert('RGB')
18
-
19
- # ประมวลผล Input (Image + Question)
20
- inputs = processor(images=image, text=question, return_tensors="pt")
21
-
22
- # สร้างคำตอบ
23
- out = model.generate(**inputs, max_length=50)
24
-
25
- # ถอดรหัสผลลัพธ์
26
- answer = processor.decode(out[0], skip_special_tokens=True)
27
- return answer
28
-
29
- except Exception as e:
30
- return f"An error occurred: {e}"
31
 
32
- # 3. สร้าง Interface ข Gradio
33
  demo = gr.Interface(
34
- fn=answer_question_on_image,
35
- inputs=[
36
- gr.Image(type="pil", label="Upload Document/Screenshot Image"),
37
- gr.Textbox(label="Question about the image (e.g., What is the graph title?)")
38
- ],
 
 
39
  outputs="text",
40
- title="Pix2Struct Visual Question Answering",
41
- description="Ask a question about an uploaded image (screenshot, document, or diagram)."
 
42
  )
43
 
44
- # 4. แอปพลิเคชัน (ถ้จะรับนเครื่องของคุณ)
45
  if __name__ == "__main__":
46
  demo.launch()
 
1
  import gradio as gr
2
+ from transformers import pipeline
 
3
 
4
+ # 1. โหลดโมเดล: เราจะใชโมเดลิเคราะห์ความรู้สึก (Sentiment Analysis) เป็นตัวอย่าง
5
+ # โมเดลนี้จะบอกว่าข้อความเป็น 'บวก' หรือ 'ลบ'
6
+ classifier = pipeline(task="sentiment-analysis")
 
7
 
8
+ # 2. ฟังก์ชันหลักสำหรับทำนายผล
9
+ def analyze_sentiment(text):
10
+ # โมเดลรับข้อความไปประมวลผล
11
+ result = classifier(text)[0]
12
+
13
+ # ส่งผลลัพธ์กลับในรูปแบบที่อ่านง่าย
14
+ label = result['label']
15
+ score = round(result['score'] * 100, 2)
16
+
17
+ return f"ผลลัพธ์: {label}, ความมั่นใจ: {score}%"
 
 
 
 
 
 
 
 
 
 
 
18
 
19
+ # 3. สร้างอินเทอร์เฟซ Gradio
20
  demo = gr.Interface(
21
+ # ฟังก์ชันที่เราต้องการให้ Gradio เรียกใช้
22
+ fn=analyze_sentiment,
23
+
24
+ # อินพุต: ให้ผู้ใช้พิมพ์ข้อความ (Textbox)
25
+ inputs=gr.Textbox(lines=2, placeholder="พิมพ์ข้อความที่คุณต้องการวิเคราะห์ความรู้สึก..."),
26
+
27
+ # เอาท์พุต: แสดงผลลัพธ์เป็นข้อความ (Text)
28
  outputs="text",
29
+
30
+ # ตั้งชื่อแอป
31
+ title="Sentiment Analysis Demo (วิเคราะห์ความรู้สึก)"
32
  )
33
 
34
+ # 4. ่งให้แอปพลิเคชันทำงาน
35
  if __name__ == "__main__":
36
  demo.launch()