File size: 12,670 Bytes
4449a29
9152906
4449a29
e15d492
 
 
 
4449a29
e15d492
 
9445e2a
e15d492
4449a29
e15d492
4449a29
 
e15d492
4449a29
 
 
e15d492
9445e2a
e15d492
9445e2a
e15d492
9445e2a
dc19a6c
e15d492
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dc19a6c
e15d492
 
 
 
dc19a6c
e15d492
 
4449a29
e15d492
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4449a29
e15d492
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4449a29
e15d492
 
 
4449a29
e15d492
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4449a29
dc19a6c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
import gradio as gr
import os
from datetime import datetime
from reportlab.lib.pagesizes import A4, landscape
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib import colors
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, Image
from reportlab.pdfgen import canvas
from reportlab.lib.units import inch, cm
from reportlab.lib.enums import TA_CENTER, TA_LEFT
from transformers import pipeline
import io

# Load AI dari Hugging Face dengan model kecil
ai_assistant = pipeline(
    "text-generation",
    model="distilgpt2"
)

def qc_ai_recommendation(job_type, notes):
    """Generate AI recommendation based on job type and inspection notes"""
    prompt = f"""
    Quality Control Inspection untuk Proyek Konstruksi. Jenis pekerjaan: {job_type}. 
    Catatan hasil inspeksi: {notes}.
    Rekomendasi tindak lanjut yang dibutuhkan:
    """
    
    try:
        result = ai_assistant(prompt, max_length=300, do_sample=True, temperature=0.7)[0]['generated_text']
        # Ekstrak respons (setelah prompt)
        response = result[len(prompt):].strip()
        if not response or len(response) < 20:
            return "Berdasarkan hasil inspeksi, direkomendasikan untuk melakukan finishing permukaan sesuai dengan standar mutu yang telah ditentukan dalam spesifikasi teknis. Pastikan pekerjaan {job_type} memenuhi kriteria toleransi dimensi dan kerapian yang disyaratkan dalam dokumen kontrak."
        return response
    except Exception as e:
        # Fallback jika model gagal
        return "Berdasarkan hasil inspeksi, direkomendasikan untuk melakukan finishing permukaan sesuai dengan standar mutu yang telah ditentukan dalam spesifikasi teknis. Pastikan pekerjaan {job_type} memenuhi kriteria toleransi dimensi dan kerapian yang disyaratkan dalam dokumen kontrak."

def ai_quality_analysis(job_type, notes):
    """Analyze quality status based on inspection notes"""
    # Kata kunci negatif yang menunjukkan masalah
    negative_keywords = ["rusak", "bocor", "retak", "tidak sesuai", "buruk", "longgar", 
                         "tidak rata", "miring", "keropos", "kotor", "perlu finishing", 
                         "perlu diperbaiki", "cacat", "kurang", "bermasalah"]
    
    # Periksa apakah ada kata kunci negatif dalam catatan
    for keyword in negative_keywords:
        if keyword.lower() in notes.lower():
            return "Tidak Lulus", f"Terdeteksi masalah: '{keyword}' dalam catatan inspeksi."
    
    # Jika tidak ada masalah terdeteksi
    return "Lulus", "Tidak ditemukan masalah signifikan dalam catatan inspeksi."

def generate_professional_pdf(project_name, location, job_type, quality_status, notes, ai_suggestion, status_reason, inspector_name="QC Inspector"):
    """Generate professional PDF report"""
    buffer = io.BytesIO()
    now = datetime.now()
    report_date = now.strftime("%Y-%m-%d")
    report_time = now.strftime("%H:%M:%S")
    report_id = now.strftime("%Y%m%d%H%M")
    
    # Create document
    doc = SimpleDocTemplate(
        buffer, 
        pagesize=A4, 
        topMargin=0.5*inch,
        leftMargin=0.5*inch,
        rightMargin=0.5*inch,
        bottomMargin=0.5*inch
    )
    
    # Styles
    styles = getSampleStyleSheet()
    styles.add(ParagraphStyle(
        name='Title',
        parent=styles['Heading1'],
        fontSize=14,
        alignment=TA_CENTER,
        spaceAfter=0.2*inch,
    ))
    
    styles.add(ParagraphStyle(
        name='Subtitle',
        parent=styles['Heading2'],
        fontSize=12,
        alignment=TA_CENTER,
        spaceAfter=0.2*inch,
    ))
    
    styles.add(ParagraphStyle(
        name='Section',
        parent=styles['Heading3'],
        fontSize=10,
        spaceAfter=0.1*inch,
        spaceBefore=0.1*inch,
    ))
    
    styles.add(ParagraphStyle(
        name='Normal_Justified',
        parent=styles['Normal'],
        alignment=4,  # Justified
        spaceAfter=0.1*inch,
    ))
    
    # Content for the document
    content = []
    
    # Header with logo (placeholder)
    header_data = [
        ["LAPORAN INSPEKSI QUALITY CONTROL", ""],
        [f"No. Laporan: QC-{report_id}", f"Tanggal: {report_date}"]
    ]
    
    t = Table(header_data, colWidths=[doc.width/2.0]*2)
    t.setStyle(TableStyle([
        ('SPAN', (0, 0), (1, 0)),
        ('ALIGN', (0, 0), (0, 0), 'CENTER'),
        ('FONT', (0, 0), (0, 0), 'Helvetica-Bold', 14),
        ('FONT', (0, 1), (1, 1), 'Helvetica', 9),
        ('ALIGN', (0, 1), (0, 1), 'LEFT'),
        ('ALIGN', (1, 1), (1, 1), 'RIGHT'),
        ('BOTTOMPADDING', (0, 0), (1, 0), 10),
        ('TOPPADDING', (0, 0), (1, 0), 10),
    ]))
    content.append(t)
    content.append(Spacer(1, 0.2*inch))
    
    # Project Information
    content.append(Paragraph("<b>INFORMASI PROYEK</b>", styles['Section']))
    
    project_data = [
        ["Nama Proyek:", project_name],
        ["Lokasi:", location],
        ["Jenis Pekerjaan:", job_type],
        ["Status Mutu:", quality_status],
    ]
    
    t = Table(project_data, colWidths=[doc.width*0.3, doc.width*0.7])
    t.setStyle(TableStyle([
        ('FONT', (0, 0), (0, -1), 'Helvetica-Bold', 9),
        ('FONT', (1, 0), (1, -1), 'Helvetica', 9),
        ('BACKGROUND', (0, 0), (0, -1), colors.lightgrey),
        ('GRID', (0, 0), (1, -1), 0.5, colors.grey),
        ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ('LEFTPADDING', (0, 0), (-1, -1), 6),
        ('RIGHTPADDING', (0, 0), (-1, -1), 6),
    ]))
    content.append(t)
    content.append(Spacer(1, 0.2*inch))
    
    # Inspection Details
    content.append(Paragraph("<b>DETAIL INSPEKSI</b>", styles['Section']))
    
    inspection_data = [
        ["Tanggal & Waktu Inspeksi:", f"{report_date} {report_time}"],
        ["Inspektor:", inspector_name],
        ["Metode Inspeksi:", "Visual & Dimensional"],
        ["Standar Referensi:", "SNI 2847:2019 / ASTM / ACI 318"],
    ]
    
    t = Table(inspection_data, colWidths=[doc.width*0.3, doc.width*0.7])
    t.setStyle(TableStyle([
        ('FONT', (0, 0), (0, -1), 'Helvetica-Bold', 9),
        ('FONT', (1, 0), (1, -1), 'Helvetica', 9),
        ('BACKGROUND', (0, 0), (0, -1), colors.lightgrey),
        ('GRID', (0, 0), (1, -1), 0.5, colors.grey),
        ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ('LEFTPADDING', (0, 0), (-1, -1), 6),
        ('RIGHTPADDING', (0, 0), (-1, -1), 6),
    ]))
    content.append(t)
    content.append(Spacer(1, 0.2*inch))
    
    # Inspection Notes
    content.append(Paragraph("<b>CATATAN INSPEKSI</b>", styles['Section']))
    
    notes_data = [
        ["Catatan:", notes],
        ["Analisis Status:", status_reason],
    ]
    
    t = Table(notes_data, colWidths=[doc.width*0.3, doc.width*0.7])
    t.setStyle(TableStyle([
        ('FONT', (0, 0), (0, -1), 'Helvetica-Bold', 9),
        ('FONT', (1, 0), (1, -1), 'Helvetica', 9),
        ('BACKGROUND', (0, 0), (0, -1), colors.lightgrey),
        ('GRID', (0, 0), (1, -1), 0.5, colors.grey),
        ('VALIGN', (0, 0), (-1, -1), 'TOP'),
        ('LEFTPADDING', (0, 0), (-1, -1), 6),
        ('RIGHTPADDING', (0, 0), (-1, -1), 6),
    ]))
    content.append(t)
    content.append(Spacer(1, 0.2*inch))
    
    # AI Recommendation
    content.append(Paragraph("<b>REKOMENDASI</b>", styles['Section']))
    
    if quality_status == "Tidak Lulus":
        recommendation_color = colors.lightcoral
    else:
        recommendation_color = colors.lightgreen
        
    recommendation_data = [
        ["Rekomendasi AI:", ai_suggestion],
    ]
    
    t = Table(recommendation_data, colWidths=[doc.width*0.3, doc.width*0.7])
    t.setStyle(TableStyle([
        ('FONT', (0, 0), (0, -1), 'Helvetica-Bold', 9),
        ('FONT', (1, 0), (1, -1), 'Helvetica', 9),
        ('BACKGROUND', (0, 0), (0, -1), colors.lightgrey),
        ('BACKGROUND', (1, 0), (1, -1), recommendation_color),
        ('GRID', (0, 0), (1, -1), 0.5, colors.grey),
        ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ('LEFTPADDING', (0, 0), (-1, -1), 6),
        ('RIGHTPADDING', (0, 0), (-1, -1), 6),
    ]))
    content.append(t)
    content.append(Spacer(1, 0.3*inch))
    
    # Signatures section
    content.append(Paragraph("<b>APPROVAL</b>", styles['Section']))
    
    signature_data = [
        ["QC Inspector", "Project Manager", "Owner Representative"],
        ["", "", ""],
        ["________________", "________________", "________________"],
        [inspector_name, "", ""],
        ["Tanggal: " + report_date, "Tanggal: ", "Tanggal: "],
    ]
    
    t = Table(signature_data, colWidths=[doc.width/3.0]*3)
    t.setStyle(TableStyle([
        ('FONT', (0, 0), (2, 0), 'Helvetica-Bold', 9),
        ('FONT', (0, 2), (2, 4), 'Helvetica', 8),
        ('ALIGN', (0, 0), (2, 4), 'CENTER'),
        ('VALIGN', (0, 0), (2, 4), 'MIDDLE'),
        ('LINEBELOW', (0, 2), (2, 2), 1, colors.black),
        ('TOPPADDING', (0, 0), (2, 0), 12),
        ('BOTTOMPADDING', (0, 0), (2, 0), 30),
        ('BOTTOMPADDING', (0, 2), (2, 2), 4),
        ('TOPPADDING', (0, 2), (2, 2), 0),
    ]))
    content.append(t)
    
    # Footer with disclaimer
    content.append(Spacer(1, 0.3*inch))
    footer_text = "Laporan ini dibuat menggunakan teknologi AI untuk membantu analisis. Rekomendasi AI harus direview oleh Quality Control Engineer yang berpengalaman. Laporan ini bukan pengganti dari penilaian profesional."
    content.append(Paragraph(footer_text, ParagraphStyle(name='Footer', parent=styles['Normal'], fontSize=7, textColor=colors.grey)))
    
    # Build the PDF
    doc.build(content)
    buffer.seek(0)
    return buffer

def generate_qc_report(project_name, location, job_type, quality_status, notes, inspector_name="QC Inspector"):
    """Generate QC report with AI recommendations"""
    # Analyze quality if not manually selected
    if not quality_status:
        quality_status, status_reason = ai_quality_analysis(job_type, notes)
    else:
        status_reason = "Status ditentukan oleh inspektor."
    
    # Get AI recommendation
    ai_suggestion = qc_ai_recommendation(job_type, notes)
    
    # Generate PDF
    pdf_buffer = generate_professional_pdf(
        project_name, 
        location, 
        job_type, 
        quality_status, 
        notes, 
        ai_suggestion, 
        status_reason, 
        inspector_name
    )
    
    # Save PDF to file
    pdf_filename = "qc_report.pdf"
    with open(pdf_filename, "wb") as f:
        f.write(pdf_buffer.getvalue())
    
    return ai_suggestion, status_reason, pdf_filename

with gr.Blocks(theme=gr.themes.Soft()) as app:
    gr.Markdown("# πŸ—οΈ QC Agent β€” Sistem Inspeksi & Rekomendasi AI Konstruksi")
    
    with gr.Row():
        with gr.Column():
            gr.Markdown("### Data Proyek")
            project_name = gr.Textbox(label="Nama Proyek", placeholder="Masukkan nama proyek")
            location = gr.Textbox(label="Lokasi Proyek", placeholder="Masukkan lokasi proyek")
            job_type = gr.Textbox(label="Jenis Pekerjaan", placeholder="Contoh: Kolom, Balok, Dinding, dll")
            inspector_name = gr.Textbox(label="Nama Inspektor", placeholder="Nama QC Inspector", value="QC Inspector")
        
        with gr.Column():
            gr.Markdown("### Data Inspeksi")
            quality_status = gr.Radio(
                ["Lulus", "Tidak Lulus"], 
                label="Status Mutu", 
                value=None,
                info="Kosongkan untuk analisis otomatis oleh AI"
            )
            notes = gr.Textbox(
                label="Catatan Inspeksi", 
                lines=4, 
                placeholder="Masukkan hasil observasi inspeksi secara detail"
            )
    
    with gr.Row():
        submit = gr.Button("πŸš€ Generate Laporan Inspeksi", variant="primary", scale=2)
    
    with gr.Row():
        with gr.Column():
            ai_output = gr.Textbox(label="πŸ’‘ Rekomendasi AI", lines=3)
            status_reason = gr.Textbox(label="πŸ” Analisis Status", lines=2)
    
    with gr.Row():
        output_pdf = gr.File(label="πŸ“₯ Laporan QC (PDF)")
    
    submit.click(
        generate_qc_report,
        inputs=[project_name, location, job_type, quality_status, notes, inspector_name],
        outputs=[ai_output, status_reason, output_pdf]
    )
    
    gr.Markdown("""
    ### Panduan Penggunaan
    1. Isi informasi proyek dan inspeksi dengan lengkap
    2. Anda dapat memilih status mutu atau mengosongkannya untuk analisis otomatis oleh AI
    3. Berikan catatan inspeksi yang detail untuk mendapatkan rekomendasi yang akurat
    4. Klik 'Generate Laporan Inspeksi' untuk mendapatkan laporan QC profesional
    """)

app.launch()