Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -8,142 +8,120 @@ from huggingface_hub import login
|
|
8 |
# Space configuration
|
9 |
SPACE_DIR = os.environ.get("HF_HOME", os.getcwd())
|
10 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
11 |
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
print(f"HF Auth Error: {e}")
|
21 |
-
return False
|
22 |
-
print("HF Auth: No token found")
|
23 |
-
return False
|
24 |
-
|
25 |
-
init_hf_auth()
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
# Configuration
|
30 |
-
MODEL_NAME = "google/gemma-2-2b-jpn-it"
|
31 |
-
PDF_PATH = "LTDOCS.pdf"
|
32 |
-
MAX_TOKENS = 512
|
33 |
-
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
34 |
-
|
35 |
-
# System prompt template
|
36 |
-
SYSTEM_PROMPT = """You are Foton...""" # Keep your original prompt
|
37 |
-
|
38 |
-
# Load PDF content with error handling
|
39 |
-
def load_pdf_content():
|
40 |
try:
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
return content.lower()
|
45 |
except Exception as e:
|
46 |
-
print(f"
|
47 |
-
return
|
48 |
|
49 |
-
|
|
|
50 |
|
51 |
-
# Initialize
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
def create_pipeline():
|
56 |
-
return pipeline(
|
57 |
"text-generation",
|
58 |
-
model=
|
59 |
-
|
60 |
model_kwargs={
|
61 |
-
"torch_dtype": torch.
|
62 |
-
"
|
63 |
-
"cache_dir": "model_cache"
|
64 |
}
|
65 |
)
|
66 |
-
|
67 |
-
try:
|
68 |
-
pipe = create_pipeline()
|
69 |
except Exception as e:
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
85 |
try:
|
86 |
-
|
|
|
|
|
|
|
|
|
87 |
prompt,
|
88 |
-
max_new_tokens=
|
89 |
-
temperature=0.
|
90 |
top_p=0.9,
|
91 |
do_sample=True,
|
92 |
-
|
93 |
-
)
|
94 |
-
|
95 |
-
# Extract only the new response
|
96 |
-
return response[len(prompt):].split("User:")[0].strip()
|
97 |
-
|
98 |
except Exception as e:
|
99 |
-
print(f"Generation
|
100 |
-
|
101 |
-
|
102 |
-
# Interface design
|
103 |
-
theme = gr.themes.Soft(
|
104 |
-
primary_hue="emerald",
|
105 |
-
secondary_hue="teal"
|
106 |
-
)
|
107 |
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
with gr.Row():
|
112 |
-
gr.Image("logo.png", width=100, show_label=False)
|
113 |
-
gr.Markdown("### Karibu kwa Huduma ya Lugha Tausi!")
|
114 |
|
115 |
chatbot = gr.Chatbot(
|
116 |
-
value=[
|
|
|
|
|
|
|
117 |
bubble_full_width=False,
|
118 |
-
|
|
|
119 |
)
|
120 |
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
)
|
127 |
-
|
128 |
-
|
129 |
-
examples = gr.Examples(
|
130 |
-
examples=[
|
131 |
-
["Nisaidie kutafsiri sentensi hii"],
|
132 |
-
["Ninauliza kuhusu sarufi ya Kiswahili"],
|
133 |
-
["Eleza maana ya 'Haraka haraka haina baraka'"]
|
134 |
-
],
|
135 |
-
inputs=msg
|
136 |
-
)
|
137 |
|
138 |
-
submit.click(respond, [msg, chatbot], [msg, chatbot])
|
139 |
msg.submit(respond, [msg, chatbot], [msg, chatbot])
|
|
|
140 |
|
141 |
-
# Deployment settings
|
142 |
if __name__ == "__main__":
|
143 |
demo.launch(
|
144 |
server_name="0.0.0.0",
|
145 |
server_port=7860,
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
|
|
8 |
# Space configuration
|
9 |
SPACE_DIR = os.environ.get("HF_HOME", os.getcwd())
|
10 |
|
11 |
+
# Load and preprocess the PDF content
|
12 |
+
try:
|
13 |
+
pdf_path = os.path.join(SPACE_DIR, "LTDOCS.pdf")
|
14 |
+
with open(pdf_path, 'rb') as file:
|
15 |
+
pdf_reader = PyPDF2.PdfReader(file)
|
16 |
+
pdf_content = ' '.join([page.extract_text() for page in pdf_reader.pages])
|
17 |
+
pdf_content = pdf_content.lower().strip()
|
18 |
+
except Exception as e:
|
19 |
+
pdf_content = ""
|
20 |
+
print(f"Error loading PDF: {e}")
|
21 |
|
22 |
+
def init_huggingface_auth():
|
23 |
+
"""Space-friendly authentication"""
|
24 |
+
token = os.getenv("HUGGINGFACE_TOKEN")
|
25 |
+
|
26 |
+
if not token:
|
27 |
+
print("No HF token found in environment")
|
28 |
+
return False
|
29 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
30 |
try:
|
31 |
+
login(token=token, add_to_git_credential=False)
|
32 |
+
print("HF authentication successful")
|
33 |
+
return True
|
|
|
34 |
except Exception as e:
|
35 |
+
print(f"Login error: {e}")
|
36 |
+
return False
|
37 |
|
38 |
+
if not init_huggingface_auth():
|
39 |
+
print("Warning: Authentication failed")
|
40 |
|
41 |
+
# Initialize the pipeline with CPU optimization
|
42 |
+
try:
|
43 |
+
pipe = pipeline(
|
|
|
|
|
|
|
44 |
"text-generation",
|
45 |
+
model="google/gemma-2-2b-jpn-it",
|
46 |
+
device_map="auto",
|
47 |
model_kwargs={
|
48 |
+
"torch_dtype": torch.float16,
|
49 |
+
"low_cpu_mem_usage": True
|
|
|
50 |
}
|
51 |
)
|
|
|
|
|
|
|
52 |
except Exception as e:
|
53 |
+
print(f"Model loading error: {e}")
|
54 |
+
raise
|
55 |
+
|
56 |
+
SYSTEM_PROMPT = f"""You are Foton, Swahili AI assistant. Tasks:
|
57 |
+
1. Swahili translations
|
58 |
+
2. Teach Swahili vocabulary/grammar
|
59 |
+
3. Explain cultural context
|
60 |
+
4. Help practice conversations
|
61 |
+
5. Programming assistance using: {pdf_content}
|
62 |
+
|
63 |
+
Maintain friendly, patient demeanor with cultural context.
|
64 |
+
"""
|
65 |
+
|
66 |
+
def format_messages(history):
|
67 |
+
"""Format chat history with system prompt"""
|
68 |
+
messages = [{"role": "system", "content": SYSTEM_PROMPT}]
|
69 |
+
for msg in history:
|
70 |
+
if isinstance(msg, dict) and "role" in msg and "content" in msg:
|
71 |
+
messages.append(msg)
|
72 |
+
return messages
|
73 |
+
|
74 |
+
def generate_response(history):
|
75 |
+
"""Generate AI response"""
|
76 |
try:
|
77 |
+
messages = format_messages(history)
|
78 |
+
|
79 |
+
prompt = "\n".join([f"{m['role']}: {m['content']}" for m in messages])
|
80 |
+
|
81 |
+
output = pipe(
|
82 |
prompt,
|
83 |
+
max_new_tokens=256,
|
84 |
+
temperature=0.1,
|
85 |
top_p=0.9,
|
86 |
do_sample=True,
|
87 |
+
return_full_text=False
|
88 |
+
)
|
89 |
+
return output[0]["generated_text"].strip()
|
|
|
|
|
|
|
90 |
except Exception as e:
|
91 |
+
print(f"Generation error: {e}")
|
92 |
+
return "Samahani, nimekutana na tatizo. Tafadhali jaribu tena baadaye."
|
|
|
|
|
|
|
|
|
|
|
|
|
93 |
|
94 |
+
# Create Gradio interface with Space optimizations
|
95 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
96 |
+
gr.Markdown("# Lugha Tausi - Swahili Assistant")
|
|
|
|
|
|
|
97 |
|
98 |
chatbot = gr.Chatbot(
|
99 |
+
value=[{"role": "assistant", "content": "**Karibu Lugha Tausi!** Mimi ni Foton, msaidizi wako wa Kiswahili. Niko hapa kukusaidia kujifunza na kuzungumza Kiswahili. **Ninaweza kukusaidiaje leo?** 😊"}],
|
100 |
+
height=600,
|
101 |
+
show_label=False,
|
102 |
+
avatar_images=(None, "user.png"),
|
103 |
bubble_full_width=False,
|
104 |
+
show_share_button=False,
|
105 |
+
type="messages"
|
106 |
)
|
107 |
|
108 |
+
msg = gr.Textbox(placeholder="Andika ujumbe wako hapa...", show_label=False)
|
109 |
+
clear = gr.Button("Futa Mazungumzo")
|
110 |
+
|
111 |
+
def respond(message, history):
|
112 |
+
history.append({"role": "user", "content": message})
|
113 |
+
bot_response = generate_response(history)
|
114 |
+
history.append({"role": "assistant", "content": bot_response})
|
115 |
+
return "", history
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
116 |
|
|
|
117 |
msg.submit(respond, [msg, chatbot], [msg, chatbot])
|
118 |
+
clear.click(lambda: [None, []], None, [msg, chatbot], queue=False)
|
119 |
|
|
|
120 |
if __name__ == "__main__":
|
121 |
demo.launch(
|
122 |
server_name="0.0.0.0",
|
123 |
server_port=7860,
|
124 |
+
auth=os.getenv("SPACE_AUTH"),
|
125 |
+
show_error=True,
|
126 |
+
share=True # Explicitly disable sharing
|
127 |
+
)
|