Spaces:
Paused
Paused
File size: 14,706 Bytes
f87cd21 db75ce3 b240945 f87cd21 856d499 f87cd21 b240945 f87cd21 b240945 513c9d0 f87cd21 513c9d0 b240945 f87cd21 856d499 f87cd21 f7f36bb f87cd21 f7f36bb f87cd21 b240945 f87cd21 f7f36bb f87cd21 f7f36bb f87cd21 db75ce3 f87cd21 5ae0001 f87cd21 db75ce3 f87cd21 db75ce3 f87cd21 db75ce3 f87cd21 db75ce3 f87cd21 db75ce3 f87cd21 | 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 | # ============================================================================
# CONTENTFORGE AI - FINAL WORKING VERSION
# Multi-modal AI platform with fine-tuned models
# ============================================================================
import gradio as gr
import torch
import os
from huggingface_hub import login
# ============================================================================
# AUTHENTICATION
# ============================================================================
HF_TOKEN = os.environ.get("HF_TOKEN")
if HF_TOKEN:
print("π Authenticating with HuggingFace...")
login(token=HF_TOKEN)
print("β
Authenticated!\n")
else:
print("β οΈ No HF_TOKEN found - some models may fail to load\n")
from transformers import (
T5Tokenizer, T5ForConditionalGeneration,
Qwen2VLForConditionalGeneration, Qwen2VLProcessor,
AutoProcessor, MusicgenForConditionalGeneration
)
from peft import PeftModel
from qwen_vl_utils import process_vision_info
from diffusers import StableDiffusionPipeline
from PIL import Image
import numpy as np
device = "cuda" if torch.cuda.is_available() else "cpu"
print(f"π₯οΈ Using device: {device}")
print("π¦ Loading models... This may take 2-3 minutes on first run.\n")
# ============================================================================
# MODEL LOADING
# ============================================================================
# 1. T5 Summarization Model
print("π Loading T5 model...")
t5_tokenizer = T5Tokenizer.from_pretrained("Bashaarat1/t5-small-arxiv-summarizer")
t5_model = T5ForConditionalGeneration.from_pretrained(
"Bashaarat1/t5-small-arxiv-summarizer"
).to(device)
t5_model.eval()
print("β
T5 loaded!")
# 2. Qwen VLM Q&A Model with YOUR LoRA adapter
print("π€ Loading Qwen2-VL base model...")
qwen_base = Qwen2VLForConditionalGeneration.from_pretrained(
"Qwen/Qwen2-VL-2B-Instruct",
device_map="auto",
torch_dtype=torch.bfloat16
)
print("π§ Loading YOUR fine-tuned LoRA adapter...")
qwen_model = PeftModel.from_pretrained(
qwen_base,
"Bashaarat1/qwen-finetuned-scienceqa"
)
qwen_processor = Qwen2VLProcessor.from_pretrained("Qwen/Qwen2-VL-2B-Instruct")
qwen_model.eval()
print("β
Qwen loaded!")
# 3. MusicGen Model
print("π΅ Loading MusicGen model...")
music_processor = AutoProcessor.from_pretrained("Bashaarat1/fine-tuned-musicgen-small")
music_model = MusicgenForConditionalGeneration.from_pretrained(
"Bashaarat1/fine-tuned-musicgen-small"
).to(device)
music_model.eval()
print("β
MusicGen loaded!")
# 4. Stable Diffusion Model
print("π¨ Loading Stable Diffusion model...")
sd_pipe = StableDiffusionPipeline.from_pretrained(
"runwayml/stable-diffusion-v1-5",
torch_dtype=torch.float16 if device == "cuda" else torch.float32,
safety_checker=None
).to(device)
print("β
Stable Diffusion loaded!")
print("\nπ All 4 models loaded successfully!\n")
# ============================================================================
# INFERENCE FUNCTIONS
# ============================================================================
def summarize_text(text, max_length=128):
"""Summarize text using fine-tuned T5"""
if not text.strip():
return "β οΈ Please enter some text to summarize."
try:
inputs = t5_tokenizer(
f"summarize: {text}",
return_tensors="pt",
max_length=512,
truncation=True
).to(device)
with torch.no_grad():
outputs = t5_model.generate(
**inputs,
max_length=max_length,
min_length=30,
num_beams=4,
early_stopping=True
)
summary = t5_tokenizer.decode(outputs[0], skip_special_tokens=True)
return f"π **Summary:**\n\n{summary}\n\n---\n*Original: {len(text.split())} words β Summary: {len(summary.split())} words*"
except Exception as e:
return f"β Error: {str(e)}"
def answer_question(question, image=None):
"""Answer question with optional image using Qwen VLM"""
if not question.strip():
return "β οΈ Please enter a question."
try:
if image is not None:
if isinstance(image, np.ndarray):
image = Image.fromarray(image).convert('RGB')
messages = [{
"role": "user",
"content": [
{"type": "image", "image": image},
{"type": "text", "text": question}
]
}]
else:
messages = [{
"role": "user",
"content": [{"type": "text", "text": question}]
}]
text_prompt = qwen_processor.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True
)
if image is not None:
img_inputs, _ = process_vision_info(messages)
inputs = qwen_processor(
text=[text_prompt],
images=img_inputs,
return_tensors="pt"
).to(device)
else:
inputs = qwen_processor(
text=[text_prompt],
return_tensors="pt"
).to(device)
with torch.no_grad():
outputs = qwen_model.generate(**inputs, max_new_tokens=200)
answer = qwen_processor.batch_decode(
outputs[:, inputs.input_ids.size(1):],
skip_special_tokens=True
)[0].strip()
return f"π‘ **Answer:**\n\n{answer}"
except Exception as e:
return f"β Error: {str(e)}"
def generate_image(prompt, negative_prompt="", num_steps=25):
"""Generate image using Stable Diffusion"""
if not prompt.strip():
return None, "β οΈ Please enter an image description."
try:
with torch.no_grad():
image = sd_pipe(
prompt,
negative_prompt=negative_prompt,
num_inference_steps=num_steps,
guidance_scale=7.5
).images[0]
return image, f"β
**Image generated!**\n\n*Prompt: {prompt}*"
except Exception as e:
return None, f"β Error: {str(e)}"
def generate_music(prompt, duration=10):
"""Generate music using MusicGen"""
if not prompt.strip():
return None, "β οΈ Please enter a music description."
try:
inputs = music_processor(
text=[prompt],
padding=True,
return_tensors="pt"
).to(device)
max_tokens = int(duration * 50)
with torch.no_grad():
audio_values = music_model.generate(**inputs, max_new_tokens=max_tokens, do_sample=True)
sampling_rate = music_model.config.audio_encoder.sampling_rate
audio_data = audio_values[0, 0].cpu().numpy()
return (sampling_rate, audio_data), f"β
**Music generated!**\n\n*Prompt: {prompt}*\n*Duration: ~{duration} seconds*"
except Exception as e:
return None, f"β Error: {str(e)}"
# ============================================================================
# GRADIO UI
# ============================================================================
with gr.Blocks(title="ContentForge AI") as demo:
gr.Markdown("""
# π¨ ContentForge AI
**Multi-modal AI platform for education and social media content generation**
Powered by state-of-the-art fine-tuned models:
- π Fine-tuned T5 (+46% improvement)
- π€ Qwen2-VL with LoRA for science Q&A
- π¨ Stable Diffusion v1.5
- π΅ Fine-tuned MusicGen
""")
with gr.Tabs():
with gr.Tab("π Education Tools"):
gr.Markdown("## AI-powered tools for learning and research")
with gr.Tab("π Text Summarizer"):
gr.Markdown("### Summarize academic papers, articles, and long texts")
with gr.Row():
with gr.Column():
sum_input = gr.Textbox(
label="Text to Summarize",
placeholder="Paste your academic paper, article, or long text here...",
lines=10
)
sum_length = gr.Slider(
minimum=50,
maximum=200,
value=128,
step=10,
label="Summary Length (words)"
)
sum_button = gr.Button("πͺ Generate Summary", variant="primary", size="lg")
with gr.Column():
sum_output = gr.Markdown(label="Summary")
gr.Examples(
examples=[
["We present a novel approach to neural network optimization using adaptive learning rates. Our method dynamically adjusts the learning rate based on gradient statistics during training. Experiments on ImageNet show 15% improvement over standard SGD with minimal computational overhead."]
],
inputs=sum_input
)
sum_button.click(
fn=summarize_text,
inputs=[sum_input, sum_length],
outputs=sum_output
)
with gr.Tab("π€ Q&A Assistant"):
gr.Markdown("### Ask questions with optional image support")
with gr.Row():
with gr.Column():
qa_question = gr.Textbox(
label="Your Question",
placeholder="Ask anything...",
lines=3
)
qa_image = gr.Image(
label="Upload Image (Optional)",
type="pil"
)
qa_button = gr.Button("π¬ Get Answer", variant="primary", size="lg")
with gr.Column():
qa_output = gr.Markdown(label="Answer")
gr.Examples(
examples=[
["What is machine learning?", None],
["Explain photosynthesis in simple terms.", None]
],
inputs=[qa_question, qa_image]
)
qa_button.click(
fn=answer_question,
inputs=[qa_question, qa_image],
outputs=qa_output
)
with gr.Tab("π¨ Social Media Tools"):
gr.Markdown("## Create stunning content for your audience")
with gr.Tab("πΌοΈ Image Generator"):
gr.Markdown("### Generate professional images from text descriptions")
with gr.Row():
with gr.Column():
img_prompt = gr.Textbox(
label="Image Description",
placeholder="Describe the image you want to generate...",
lines=3
)
img_negative = gr.Textbox(
label="Negative Prompt (Optional)",
placeholder="What to avoid (e.g., blur, low quality, distorted)",
lines=2
)
img_steps = gr.Slider(
minimum=10,
maximum=50,
value=25,
step=5,
label="Quality (inference steps)"
)
img_button = gr.Button("π¨ Generate Image", variant="primary", size="lg")
with gr.Column():
img_output = gr.Image(label="Generated Image")
img_status = gr.Markdown()
gr.Examples(
examples=[
["A serene mountain landscape at sunset, photorealistic, 4k"]
],
inputs=img_prompt
)
img_button.click(
fn=generate_image,
inputs=[img_prompt, img_negative, img_steps],
outputs=[img_output, img_status]
)
with gr.Tab("π΅ Music Generator"):
gr.Markdown("### Generate royalty-free music from text descriptions")
with gr.Row():
with gr.Column():
music_prompt = gr.Textbox(
label="Music Description",
placeholder="Describe the music you want (mood, genre, instruments)...",
lines=3
)
music_duration = gr.Slider(
minimum=5,
maximum=20,
value=10,
step=5,
label="Duration (seconds)"
)
music_button = gr.Button("πΌ Generate Music", variant="primary", size="lg")
with gr.Column():
music_output = gr.Audio(label="Generated Music")
music_status = gr.Markdown()
gr.Examples(
examples=[
["upbeat electronic dance music with energetic drums"]
],
inputs=music_prompt
)
music_button.click(
fn=generate_music,
inputs=[music_prompt, music_duration],
outputs=[music_output, music_status]
)
gr.Markdown("""
---
**About ContentForge AI**
Multi-modal AI platform demonstrating fine-tuned models for education and social media.
*Built with β€οΈ using Gradio and Transformers*
""")
if __name__ == "__main__":
demo.launch() |