phxdev commited on
Commit
a4f7581
·
verified ·
1 Parent(s): 62cc85a

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +6 -235
app.py CHANGED
@@ -1,235 +1,6 @@
1
- import gradio as gr
2
- from transformers import pipeline
3
- import torch
4
- import os
5
-
6
- # Initialize the text generation pipeline
7
- generator = None
8
-
9
- def initialize_model():
10
- global generator
11
- try:
12
- # Use Qwen 2.5-Omni-7B - state-of-the-art multimodal model
13
- device = 0 if torch.cuda.is_available() else -1
14
- generator = pipeline(
15
- "text-generation",
16
- model="Qwen/Qwen2.5-Omni-7B",
17
- device=device,
18
- torch_dtype=torch.bfloat16 if torch.cuda.is_available() else torch.float32,
19
- trust_remote_code=True,
20
- model_kwargs={"attn_implementation": "flash_attention_2"} if torch.cuda.is_available() else {}
21
- )
22
- return f"Qwen 2.5-Omni-7B loaded successfully on {'GPU' if device == 0 else 'CPU'}!"
23
- except Exception as e:
24
- # Fallback to regular Qwen 7B instruct
25
- try:
26
- device = 0 if torch.cuda.is_available() else -1
27
- generator = pipeline(
28
- "text-generation",
29
- model="Qwen/Qwen2.5-7B-Instruct",
30
- device=device,
31
- torch_dtype=torch.bfloat16 if torch.cuda.is_available() else torch.float32,
32
- trust_remote_code=True
33
- )
34
- return f"Fallback model (Qwen 2.5-7B-Instruct) loaded on {'GPU' if device == 0 else 'CPU'}!"
35
- except Exception as e2:
36
- # Final fallback to 1.5B model
37
- try:
38
- generator = pipeline(
39
- "text-generation",
40
- model="Qwen/Qwen2.5-1.5B-Instruct",
41
- device=-1,
42
- torch_dtype=torch.float32,
43
- trust_remote_code=True
44
- )
45
- return "Final fallback model (Qwen 2.5-1.5B-Instruct) loaded on CPU!"
46
- except Exception as e3:
47
- return f"All models failed: Omni: {str(e)}, 7B: {str(e2)}, 1.5B: {str(e3)}"
48
-
49
- def generate_onepager(topic, target_audience, key_points, tone, length):
50
- if generator is None:
51
- return "Error: Model not initialized. Please wait for the model to load."
52
-
53
- # Create a structured prompt for one-pager generation
54
- length_tokens = {"Short": 200, "Medium": 400, "Long": 600}
55
- max_tokens = length_tokens.get(length, 400)
56
-
57
- # Create an optimized prompt for Qwen 2.5 instruction format
58
- prompt = f"""<|im_start|>system
59
- You are a professional document writer specializing in creating concise, well-structured one-page business documents.
60
- <|im_end|>
61
- <|im_start|>user
62
- Create a professional one-page document about "{topic}" targeted at {target_audience}.
63
-
64
- Requirements:
65
- - Tone: {tone.lower()}
66
- - Key points to include: {key_points}
67
- - Length: {length}
68
- - Format: Use clear headers and bullet points
69
- - Structure: Title, Executive Summary, Key Points, Benefits, Recommendations, Conclusion
70
-
71
- Please write the complete one-page document now.
72
- <|im_end|>
73
- <|im_start|>assistant
74
- # {topic}
75
-
76
- ## Executive Summary
77
-
78
- """
79
-
80
- try:
81
- # Generate the one-pager
82
- result = generator(
83
- prompt,
84
- max_length=len(prompt.split()) + max_tokens,
85
- num_return_sequences=1,
86
- temperature=0.8,
87
- do_sample=True,
88
- pad_token_id=generator.tokenizer.eos_token_id,
89
- eos_token_id=generator.tokenizer.eos_token_id,
90
- repetition_penalty=1.1
91
- )
92
-
93
- # Extract the generated text
94
- generated_text = result[0]['generated_text']
95
-
96
- # Clean up the output
97
- onepager = generated_text.replace(prompt, "").strip()
98
-
99
- # If output is too short, provide a structured fallback
100
- if len(onepager) < 50:
101
- onepager = create_structured_onepager(topic, target_audience, key_points, tone)
102
-
103
- return onepager
104
-
105
- except Exception as e:
106
- # Fallback to structured template
107
- return create_structured_onepager(topic, target_audience, key_points, tone)
108
-
109
- def create_structured_onepager(topic, target_audience, key_points, tone):
110
- """Create a structured one-pager when AI generation fails"""
111
-
112
- tone_styles = {
113
- "Professional": "formal and business-oriented",
114
- "Casual": "friendly and approachable",
115
- "Academic": "scholarly and research-focused",
116
- "Persuasive": "compelling and action-oriented",
117
- "Informative": "clear and educational"
118
- }
119
-
120
- style_desc = tone_styles.get(tone, "professional")
121
-
122
- template = f"""# {topic}
123
-
124
- ## Executive Summary
125
- This document provides a comprehensive overview of {topic.lower()} tailored for {target_audience.lower()}. The content is presented in a {style_desc} manner to ensure maximum impact and understanding.
126
-
127
- ## Key Points
128
-
129
- {chr(10).join([f"• {point.strip()}" for point in key_points.split(',') if point.strip()])}
130
-
131
- ## Background
132
- {topic} represents an important area that requires careful consideration and strategic thinking. Understanding the core concepts and implications is essential for {target_audience.lower()}.
133
-
134
- ## Main Content
135
- The fundamental aspects of {topic.lower()} encompass several critical areas that directly impact stakeholders. These elements work together to create a comprehensive framework for understanding and implementation.
136
-
137
- ## Benefits & Opportunities
138
- - Enhanced understanding of core concepts
139
- - Improved decision-making capabilities
140
- - Strategic advantages for implementation
141
- - Clear actionable insights
142
-
143
- ## Recommendations
144
- 1. Begin with thorough analysis of current situation
145
- 2. Develop comprehensive implementation strategy
146
- 3. Monitor progress and adjust approach as needed
147
- 4. Measure results and iterate for continuous improvement
148
-
149
- ## Conclusion
150
- {topic} offers significant opportunities for {target_audience.lower()} when approached strategically. The key points outlined above provide a solid foundation for moving forward with confidence and clarity.
151
-
152
- ---
153
- *This one-pager was generated to provide quick, actionable insights on {topic.lower()}.*"""
154
-
155
- return template
156
-
157
- # Create the Gradio interface
158
- def create_interface():
159
- with gr.Blocks(title="One-Pager Generator", theme=gr.themes.Soft()) as demo:
160
- gr.Markdown("# 📄 AI One-Pager Generator")
161
- gr.Markdown("Generate professional one-page documents on any topic using AI!")
162
-
163
- with gr.Row():
164
- with gr.Column(scale=1):
165
- topic_input = gr.Textbox(
166
- label="Topic",
167
- placeholder="e.g., Digital Marketing Strategy, Climate Change Solutions, etc.",
168
- lines=2,
169
- value="Artificial Intelligence in Healthcare"
170
- )
171
-
172
- audience_input = gr.Textbox(
173
- label="Target Audience",
174
- placeholder="e.g., Business executives, Students, General public, etc.",
175
- lines=1,
176
- value="Healthcare professionals"
177
- )
178
-
179
- keypoints_input = gr.Textbox(
180
- label="Key Points to Cover",
181
- placeholder="Enter main points separated by commas",
182
- lines=4,
183
- value="Machine learning applications, Data privacy, Cost-effectiveness, Implementation challenges"
184
- )
185
-
186
- tone_dropdown = gr.Dropdown(
187
- choices=["Professional", "Casual", "Academic", "Persuasive", "Informative"],
188
- label="Tone",
189
- value="Professional"
190
- )
191
-
192
- length_dropdown = gr.Dropdown(
193
- choices=["Short", "Medium", "Long"],
194
- label="Length",
195
- value="Medium"
196
- )
197
-
198
- generate_btn = gr.Button("🚀 Generate One-Pager", variant="primary")
199
-
200
- with gr.Column(scale=2):
201
- output_text = gr.Textbox(
202
- label="Generated One-Pager",
203
- lines=25,
204
- max_lines=35,
205
- show_copy_button=True,
206
- placeholder="Your generated one-pager will appear here..."
207
- )
208
-
209
- with gr.Row():
210
- gr.Markdown("""
211
- ### 💡 Tips for Best Results:
212
- - **Be specific** with your topic for more targeted content
213
- - **Include 3-5 key points** separated by commas
214
- - **Choose the right tone** for your intended audience
215
- - **Use descriptive audience** details (e.g., "C-level executives" vs "executives")
216
- """)
217
-
218
- # Connect the generate button to the function
219
- generate_btn.click(
220
- fn=generate_onepager,
221
- inputs=[topic_input, audience_input, keypoints_input, tone_dropdown, length_dropdown],
222
- outputs=output_text
223
- )
224
-
225
- return demo
226
-
227
- # Initialize model and launch
228
- if __name__ == "__main__":
229
- print("🚀 Starting One-Pager Generator...")
230
- print("📥 Loading AI model...")
231
- initialize_model()
232
- print("✅ Model loaded! Launching interface...")
233
-
234
- demo = create_interface()
235
- demo.launch()
 
1
+ torch
2
+ transformers
3
+ gradio
4
+ huggingface_hub
5
+ tokenizers
6
+ accelerate