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
 
 
 
6462db2
d71c6e7
 
 
 
 
 
 
 
6462db2
d71c6e7
 
 
 
 
 
 
 
 
 
 
af1eb11
d71c6e7
 
 
 
 
 
 
 
 
911a8a7
d71c6e7
af1eb11
 
ff0ca65
af1eb11
 
 
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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
import gradio as gr
from transformers import AutoTokenizer, AutoModelForCausalLM
import langextract as lx
import json
import re
from typing import List, Dict, Any, Tuple, Optional
import pandas as pd
import requests
import time
import os
from pathlib import Path
import tempfile
import torch
import spaces

# Global variables to store the loaded model and tokenizer
dental_model = None
dental_tokenizer = None
current_token = None
output_directory = Path(".")

def load_dental_transformers_model():
    """Load the dental model using transformers"""
    global dental_model, dental_tokenizer
    if dental_model is None or dental_tokenizer is None:
        try:
            print("Loading transformers model... This may take a moment on first run.")
            
            # Load tokenizer and model
            dental_tokenizer = AutoTokenizer.from_pretrained("yasserrmd/DentaInstruct-1.2B")
            dental_model = AutoModelForCausalLM.from_pretrained(
                "yasserrmd/DentaInstruct-1.2B",
                torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
                device_map="auto" if torch.cuda.is_available() else None
            )
            
            # Set pad token if not set
            if dental_tokenizer.pad_token is None:
                dental_tokenizer.pad_token = dental_tokenizer.eos_token
            
            print("Model loaded successfully!")
            return dental_model, dental_tokenizer
        except Exception as e:
            print(f"Error loading transformers model: {str(e)}")
            return None, None
    return dental_model, dental_tokenizer


@spaces.GPU(duration=120)
def generate_dental_response(
    question: str, 
    max_tokens: int = 2048, 
    temperature: float = 0.7
) -> str:
    """Generate response using transformers model"""
    
    # Load model and tokenizer
    model, tokenizer = load_dental_transformers_model()
    if not model or not tokenizer:
        return "❌ Transformers model not available."
    
    try:
        system_prompt = """You are a dental AI assistant. When providing medication recommendations, you must:
1. Always provide a complete 3-day medication regimen
2. Include detailed descriptions for each medication including exact dosage amounts, frequency, duration, mechanism of action
3. Organize the response clearly with medication names, dosages, and instructions
4. Always include a disclaimer about professional medical consultation"""
        
        messages = [
            {"role": "system", "content": system_prompt},
            {"role": "user", "content": question}
        ]
        
        # Apply chat template
        try:
            # Try with chat template first
            input_text = tokenizer.apply_chat_template(
                messages,
                add_generation_prompt=True,
                tokenize=False
            )
        except:
            # Fallback to simple concatenation if chat template fails
            input_text = f"{system_prompt}\n\nUser: {question}\n\nAssistant:"
        
        # Tokenize the input
        inputs = tokenizer(
            input_text,
            return_tensors="pt",
            padding=True,
            truncation=True,
            max_length=2048
        )
        
        # Remove token_type_ids if present (not needed for most models)
        if 'token_type_ids' in inputs:
            del inputs['token_type_ids']
        
        # Move to device
        inputs = {k: v.to(model.device) for k, v in inputs.items()}
        
        # Generate response
        with torch.no_grad():
            outputs = model.generate(
                input_ids=inputs['input_ids'],
                attention_mask=inputs['attention_mask'],
                max_new_tokens=max_tokens,
                temperature=temperature,
                top_p=0.9,
                do_sample=True,
                pad_token_id=tokenizer.eos_token_id,
                eos_token_id=tokenizer.eos_token_id
            )
        
        # Decode only the new tokens (response)
        response = tokenizer.decode(
            outputs[0][inputs['input_ids'].shape[-1]:], 
            skip_special_tokens=True
        )
        
        return response.strip()
        
    except Exception as e:
        return f"❌ Error generating response with transformers model: {str(e)}"

def extract_medications(text: str, gemini_api_key: str = "") -> Tuple[str, str, str]:
    """Extract medication information from text"""
    try:
        # Check if API key is provided
        if not gemini_api_key or not gemini_api_key.strip():
            return "❌ Please provide a valid Gemini API key for medication extraction.", text, ""
        
        model_api_key = gemini_api_key.strip()
        
        prompt_description = "Extract medication information including medication name, dosage, route, frequency, and duration in the order they appear in the text."
        
        examples = [
            lx.data.ExampleData(
                text="Patient was given 250 mg IV Cefazolin TID for one week.",
                extractions=[
                    lx.data.Extraction(extraction_class="dosage", extraction_text="250 mg"),
                    lx.data.Extraction(extraction_class="route", extraction_text="IV"),
                    lx.data.Extraction(extraction_class="medication", extraction_text="Cefazolin"),
                    lx.data.Extraction(extraction_class="frequency", extraction_text="TID"),
                    lx.data.Extraction(extraction_class="duration", extraction_text="for one week")
                ]
            )
        ]
        
        result = lx.extract(
            text_or_documents=text,
            prompt_description=prompt_description,
            examples=examples,
            model_id="gemini-2.0-flash-exp",
            api_key=model_api_key
        )
        
        if result and result.extractions:
            # Create DataFrame for display
            extraction_data = []
            for entity in result.extractions:
                position_info = ""
                if entity.char_interval:
                    start, end = entity.char_interval.start_pos, entity.char_interval.end_pos
                    position_info = f"{start}-{end}"
                
                extraction_data.append({
                    "Type": entity.extraction_class.capitalize(),
                    "Text": entity.extraction_text,
                    "Position": position_info
                })
            
            df = pd.DataFrame(extraction_data)
            
            # Create highlighted text
            highlighted_text = highlight_text_with_extractions(text, result.extractions)
            
            # Save and visualize the results
            try:
                lx.io.save_annotated_documents([result], output_name="medical_ner_extraction.jsonl", output_dir=output_directory)
                
                # Generate the interactive visualization
                html_content = lx.visualize("medical_ner_extraction.jsonl")
                
                return df.to_string(index=False), highlighted_text, html_content
                
            except Exception as viz_error:
                # If visualization fails, still return the other results
                return df.to_string(index=False), highlighted_text, f"⚠️ Visualization generation failed: {str(viz_error)}"
        else:
            return "ℹ️ No medications found in the text.", text, ""
            
    except Exception as e:
        return f"❌ Error extracting medications: {str(e)}", text, ""

def highlight_text_with_extractions(text: str, extractions: List[Any]) -> str:
    """Highlight extracted entities in the original text"""
    if not extractions:
        return text
    
    # Sort extractions by position to avoid overlap issues
    sorted_extractions = sorted(
        [e for e in extractions if e.char_interval], 
        key=lambda x: x.char_interval.start_pos
    )
    
    highlighted_text = text
    offset = 0
    
    for extraction in sorted_extractions:
        start = extraction.char_interval.start_pos + offset
        end = extraction.char_interval.end_pos + offset
        
        original = highlighted_text[start:end]
        highlighted = f'**[{extraction.extraction_class.upper()}]** {original} **[/{extraction.extraction_class.upper()}]**'
        
        highlighted_text = highlighted_text[:start] + highlighted + highlighted_text[end:]
        offset += len(highlighted) - len(original)
    
    return highlighted_text

def dental_consultation_interface(
    question: str,
    max_tokens: int,
    temperature: float
) -> str:
    """Main interface for dental consultation"""
    if not question.strip():
        return "Please enter a question first."
    
    response = generate_dental_response(
        question=question,
        max_tokens=max_tokens,
        temperature=temperature
    )
    
    token_count = len(response.split())
    return f"{response}\n\n---\nπŸ“Š Response length: ~{token_count} words"

def medication_extraction_interface(text: str, gemini_api_key: str) -> Tuple[str, str, str]:
    """Interface for medication extraction"""
    if not text.strip():
        return "Please enter text for medication extraction.", "", ""
    
    return extract_medications(text, gemini_api_key)

# Quick question options
QUICK_QUESTIONS = [
    "I have a toothache with throbbing pain, provide 3-day medication",
    "What causes tooth pain and how to treat it?",
    "How to prevent cavities?",
    "What are the signs of gum disease?",
    "Emergency dental care advice",
    "Post-extraction care instructions with medications",
    "Wisdom tooth pain relief medication regimen"
]

def create_gradio_interface():
    """Create the main Gradio interface"""
    
    # Custom CSS
    css = """
    .gradio-container {
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    }
    .main-header {
        text-align: center;
        background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
        color: white;
        padding: 2rem;
        border-radius: 10px;
        margin-bottom: 2rem;
    }
    .disclaimer {
        background-color: #fff3cd;
        border: 1px solid #ffeaa7;
        border-radius: 5px;
        padding: 1rem;
        margin: 1rem 0;
        color: #856404;
    }
    """
    
    with gr.Blocks(css=css, title="🦷 Dental AI Assistant") as demo:
        
        # Header
        gr.HTML("""
        <div class="main-header">
            <h1>🦷 Dental AI Assistant</h1>
            <p>Advanced dental consultation and medication extraction</p>
        </div>
        """)
        
        with gr.Tabs():
            # Tab 1: Dental Consultation
            with gr.TabItem("πŸ’¬ Dental Consultation"):
                with gr.Row():
                    with gr.Column(scale=2):
                        question_input = gr.Textbox(
                            label="Ask your dental question:",
                            placeholder="e.g., I have a toothache, what should I do?",
                            lines=3
                        )
                        
                        quick_question = gr.Dropdown(
                            choices=[""] + QUICK_QUESTIONS,
                            label="Or select a quick question:",
                            value=""
                        )
                        
                        # Update question input when quick question is selected
                        quick_question.change(
                            fn=lambda x: x if x else "",
                            inputs=[quick_question],
                            outputs=[question_input]
                        )
                        
                        with gr.Row():
                            consult_btn = gr.Button("πŸ” Get Dental Advice", variant="primary")
                            clear_btn = gr.Button("πŸ—‘οΈ Clear")
                    
                    with gr.Column(scale=1):
                        gr.Markdown("### βš™οΈ Settings")
                        
                        max_tokens = gr.Slider(
                            minimum=500,
                            maximum=4000,
                            value=2048,
                            step=100,
                            label="Max Response Tokens"
                        )
                        
                        temperature = gr.Slider(
                            minimum=0.1,
                            maximum=1.0,
                            value=0.7,
                            step=0.1,
                            label="Temperature (Creativity)"
                        )
                        
                        gr.Markdown("""
                        **Model Info:**
                        - Using Transformers Model
                        - Optimized for GPU/CPU
                        - Auto device mapping
                        """)
                
                response_output = gr.Textbox(
                    label="🩺 AI Response:",
                    lines=15,
                    max_lines=25
                )
                
                consult_btn.click(
                    fn=dental_consultation_interface,
                    inputs=[question_input, max_tokens, temperature],
                    outputs=[response_output]
                )
                
                clear_btn.click(
                    fn=lambda: ("", "", ""),
                    inputs=[],
                    outputs=[question_input, response_output]
                )
            
            # Tab 2: Medication Extraction
            with gr.TabItem("πŸ’Š Medication Extraction"):
                with gr.Row():
                    with gr.Column():
                        extraction_text = gr.Textbox(
                            label="Enter text for medication extraction:",
                            placeholder="Paste medical text here to extract medication information...",
                            lines=10
                        )
                        
                        gemini_api_key = gr.Textbox(
                            label="πŸ”‘ Gemini API Key",
                            placeholder="AIza...",
                            type="password",
                            info="Required for medication extraction"
                        )
                        
                        with gr.Row():
                            extract_btn = gr.Button("🧬 Extract Medications", variant="primary")
                            copy_from_consultation = gr.Button("πŸ“‹ Copy from Consultation")
                
                with gr.Row():
                    with gr.Column():
                        extraction_results = gr.Textbox(
                            label="πŸ“‹ Extracted Medications:",
                            lines=8
                        )
                    
                    with gr.Column():
                        highlighted_text = gr.Textbox(
                            label="🎯 Highlighted Text:",
                            lines=8
                        )
                
                with gr.Row():
                    visualization_html = gr.HTML(
                        label="🎨 Interactive Visualization:",
                        value="<p style='text-align: center; color: #666;'>Visualization will appear here after extraction</p>"
                    )
                
                extract_btn.click(
                    fn=medication_extraction_interface,
                    inputs=[extraction_text, gemini_api_key],
                    outputs=[extraction_results, highlighted_text, visualization_html]
                )
                
                # Copy response from consultation tab to extraction
                copy_from_consultation.click(
                    fn=lambda x: x,
                    inputs=[response_output],
                    outputs=[extraction_text]
                )
            
            # Tab 3: Help & Setup
            with gr.TabItem("πŸ“š Help & Setup"):
                gr.Markdown("""
                ## πŸš€ Getting Started
                
                ### Model:
                **Transformers Model**: Uses HuggingFace transformers library with automatic device mapping
                
                ### πŸ”‘ API Key Setup:
                
                **Gemini API Key** (required for medication extraction):
                1. Go to [Google AI Studio](https://aistudio.google.com)
                2. Click 'Get API Key'
                3. Create a new API key
                
                ### πŸ“¦ Installation Requirements:
                ```bash
                pip install gradio transformers langextract pandas requests torch
                ```
                
                ### 🩺 Features:
                - **Dental Consultation**: Get AI-powered dental advice with detailed medication regimens
                - **Medication Extraction**: Extract and highlight medications from medical text
                - **Interactive Visualization**: Visual representation of extracted medication entities
                - **Quick Questions**: Pre-built common dental questions
                - **Customizable Settings**: Adjust response length and creativity
                - **GPU/CPU Support**: Automatic device detection and optimization
                
                ### ⚠️ Important Disclaimer:
                This AI assistant is for educational purposes only. Always consult with a qualified dentist for professional medical advice.
                """)
        
        # Footer
        gr.HTML("""
        <div class="disclaimer">
            <p><strong>⚠️ Disclaimer:</strong> This AI assistant is for educational purposes only. 
            Always consult with a qualified dentist for professional medical advice.</p>
            <p style="text-align: center; margin-top: 1rem;">
                🦷 Built with Gradio | Gemini | Powered by yasserrmd/DentaInstruct-1.2B
            </p>
        </div>
        """)
    
    return demo

if __name__ == "__main__":
    # Create and launch the interface
    demo = create_gradio_interface()
    demo.queue()
    demo.launch(
            server_name="0.0.0.0",
            server_port=7860,
            share=False,
            show_error=True,
            ssr_mode=False  # Disable SSR for Spaces compatibility
        )