Wewoo commited on
Commit
f0d1550
·
verified ·
1 Parent(s): 78d0c03

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +118 -78
app.py CHANGED
@@ -1,78 +1,118 @@
1
- import gradio as gr
2
- import pandas as pd
3
- import joblib
4
- from huggingface_hub import hf_hub_download
5
- from datetime import datetime
6
- import os
7
-
8
- # Load pretrained XGBoost model từ HF Hub
9
- model_path = hf_hub_download(
10
- repo_id="sdaoudi/house-price-regression-xgb",
11
- filename="xgb_model.pkl"
12
- )
13
- model = joblib.load(model_path)
14
-
15
- # Tạo folder lưu lịch sử nếu chưa tồn tại
16
- if not os.path.exists("history"):
17
- os.makedirs("history")
18
-
19
- def predict_price(
20
- bedrooms, bathrooms, sqft_living, sqft_lot, floors,
21
- waterfront, view, condition, grade, yr_built, zipcode, lat, long
22
- ):
23
- data = {
24
- "bedrooms": [bedrooms],
25
- "bathrooms": [bathrooms],
26
- "sqft_living": [sqft_living],
27
- "sqft_lot": [sqft_lot],
28
- "floors": [floors],
29
- "waterfront": [int(waterfront)],
30
- "view": [view],
31
- "condition": [condition],
32
- "grade": [grade],
33
- "yr_built": [yr_built],
34
- "zipcode": [zipcode],
35
- "lat": [lat],
36
- "long": [long]
37
- }
38
-
39
- df = pd.DataFrame(data)
40
- pred = model.predict(df)[0]
41
- result_text = f"💰 Giá nhà dự đoán: {pred:,.0f} USD"
42
-
43
- # Lưu lịch sử dự đoán
44
- df['predicted_price'] = pred
45
- df['timestamp'] = datetime.now()
46
- history_file = "history/predictions.csv"
47
- if os.path.exists(history_file):
48
- df.to_csv(history_file, mode='a', header=False, index=False)
49
- else:
50
- df.to_csv(history_file, index=False)
51
-
52
- return result_text
53
-
54
- # Theme Gradio đẹp + tooltip
55
- interface = gr.Interface(
56
- fn=predict_price,
57
- inputs=[
58
- gr.Number(label="Bedrooms", info="Số phòng ngủ"),
59
- gr.Number(label="Bathrooms", info="Số phòng tắm"),
60
- gr.Number(label="Sqft Living", info="Diện tích sử dụng (sqft)"),
61
- gr.Number(label="Sqft Lot", info="Diện tích mảnh đất (sqft)"),
62
- gr.Number(label="Floors", info="Số tầng của nhà"),
63
- gr.Checkbox(label="Waterfront", info="Nhà có view ra nước? (tick nếu có)"),
64
- gr.Number(label="View", info="Chất lượng view (0-4)"),
65
- gr.Number(label="Condition", info="Tình trạng nhà (1-5)"),
66
- gr.Number(label="Grade", info="Chất lượng xây dựng (1-13)"),
67
- gr.Number(label="Year Built", info="Năm xây dựng"),
68
- gr.Number(label="Zipcode", info="Mã bưu chính"),
69
- gr.Number(label="Latitude", info="Vĩ độ"),
70
- gr.Number(label="Longitude", info="Kinh độ"),
71
- ],
72
- outputs="text",
73
- title="🏡 House Price Predictor (Enhanced)",
74
- description="Dự đoán giá nhà bằng XGBoost pretrained từ HuggingFace.\nLưu lịch sử dự đoán để xuất CSV.",
75
- theme="default" # Gradio mới hỗ trợ theme: default, soft, compact, etc.
76
- )
77
-
78
- interface.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import pipeline
3
+ from langdetect import detect
4
+ import docx
5
+ from pypdf import PdfReader
6
+
7
+ # ========================
8
+ # Load models
9
+ # ========================
10
+
11
+ # English summarizer
12
+ summarizer_en = pipeline("summarization", model="facebook/bart-large-cnn")
13
+
14
+ # Vietnamese summarizer
15
+ summarizer_vi = pipeline("summarization", model="VietAI/vit5-base-vietnamese-summarization")
16
+
17
+ # Quiz generator
18
+ quiz_generator = pipeline("text2text-generation", model="google/flan-t5-base")
19
+
20
+ # ========================
21
+ # Read file
22
+ # ========================
23
+
24
+ def extract_text(file):
25
+ if file.name.endswith(".pdf"):
26
+ reader = PdfReader(file)
27
+ text = ""
28
+ for page in reader.pages:
29
+ if page.extract_text():
30
+ text += page.extract_text() + "\n"
31
+ return text
32
+
33
+ elif file.name.endswith(".docx"):
34
+ doc = docx.Document(file)
35
+ return "\n".join([para.text for para in doc.paragraphs])
36
+
37
+ elif file.name.endswith(".txt"):
38
+ return file.read().decode("utf-8")
39
+
40
+ else:
41
+ return "Unsupported file format"
42
+
43
+ # ========================
44
+ # Main AI function
45
+ # ========================
46
+
47
+ def summarize_and_quiz(file, num_questions):
48
+
49
+ text = extract_text(file)
50
+
51
+ if len(text) < 200:
52
+ return "Văn bản quá ngắn / Text too short", ""
53
+
54
+ # --- Detect language ---
55
+ lang = detect(text)
56
+
57
+ # --- Choose summarizer ---
58
+ if lang == "vi":
59
+ summary = summarizer_vi(
60
+ text,
61
+ max_length=200,
62
+ min_length=80,
63
+ do_sample=False
64
+ )[0]["summary_text"]
65
+
66
+ prompt = f"""
67
+ Tạo {num_questions} câu hỏi trắc nghiệm ngắn gọn dựa vào nội dung sau:
68
+
69
+ {summary}
70
+
71
+ Mỗi câu có đáp án đúng.
72
+ """
73
+
74
+ else:
75
+ summary = summarizer_en(
76
+ text,
77
+ max_length=200,
78
+ min_length=80,
79
+ do_sample=False
80
+ )[0]["summary_text"]
81
+
82
+ prompt = f"""
83
+ Create {num_questions} multiple-choice questions based on the following content:
84
+
85
+ {summary}
86
+
87
+ Each question must include the correct answer.
88
+ """
89
+
90
+ quiz = quiz_generator(prompt, max_length=512)[0]["generated_text"]
91
+
92
+ return summary, quiz
93
+
94
+
95
+ # ========================
96
+ # Gradio Interface
97
+ # ========================
98
+
99
+ interface = gr.Interface(
100
+ fn=summarize_and_quiz,
101
+
102
+ inputs=[
103
+ gr.File(label="📄 Upload PDF / DOCX / TXT"),
104
+ gr.Slider(5, 10, value=5, step=1, label="Số câu hỏi Quiz")
105
+ ],
106
+
107
+ outputs=[
108
+ gr.Textbox(label="📌 Tóm tắt nội dung", lines=8),
109
+ gr.Textbox(label="📝 Quiz tự động tạo", lines=12)
110
+ ],
111
+
112
+ title="📚 AI TÓM TẮT & TẠO QUIZ (VIỆT + ANH)",
113
+ description="""
114
+ AI tự động nhận diện ngôn ngữ và tóm tắt tài liệu (Việt/Anh), sau đó tạo quiz giúp sinh viên ghi nhớ nhanh.
115
+ """
116
+ )
117
+
118
+ interface.launch()