ghostai1 commited on
Commit
56959f4
Β·
verified Β·
1 Parent(s): 0c0b128

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +42 -117
app.py CHANGED
@@ -1,124 +1,49 @@
1
- import gradio as gr
2
- from transformers import pipeline
3
- import numpy as np
4
- from PIL import Image
5
- import io
6
- import base64
7
 
8
- # Initialize the sentiment analysis pipeline (using a lightweight model for CPU)
9
- sentiment_analyzer = pipeline("sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english")
 
 
 
 
 
 
 
 
10
 
11
- # Mock text-to-image function (simulates image generation for CPU compatibility)
12
- def generate_mock_image(text_prompt, width=200, height=200):
13
- # Create a simple gradient image as a placeholder (to avoid heavy dependencies)
14
- img_array = np.zeros((height, width, 3), dtype=np.uint8)
15
- for i in range(height):
16
- for j in range(width):
17
- img_array[i, j] = [(i % 255), (j % 255), ((i + j) % 255)] # RGB gradient
18
- img = Image.fromarray(img_array)
19
-
20
- # Save image to a buffer for Gradio
21
- buffered = io.BytesIO()
22
- img.save(buffered, format="PNG")
23
- img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
24
- return f"data:image/png;base64,{img_str}"
25
 
26
- # Function for sentiment analysis
27
- def analyze_sentiment(text):
28
- if not text.strip():
29
- return "Please enter some text."
30
- result = sentiment_analyzer(text)[0]
31
- label = result['label']
32
- score = result['score']
33
- return f"Sentiment: {label} (Confidence: {score:.2%})"
 
 
 
 
34
 
35
- # Chatbot-style feedback function
36
- def chatbot_response(user_feedback, chat_history):
37
- if not user_feedback.strip():
38
- return chat_history, "Please provide feedback."
39
- # Append user feedback and a simple bot response
40
- chat_history.append((user_feedback, f"Thanks for your feedback! I understood: '{user_feedback}'."))
41
- return chat_history, ""
42
 
43
- # Main Gradio app using Blocks for advanced layout
44
- with gr.Blocks(css=".gradio-container {background-color: #f0f4f8;} .block {border-radius: 8px; padding: 10px;}") as demo:
45
- gr.Markdown(
46
- """
47
- # Welcome to the Multi-Feature Gradio App! πŸš€
48
- This app combines **sentiment analysis**, **text-to-image generation**, and a **feedback chatbot**.
49
- Built for Hugging Face Spaces (free tier, CPU-only).
50
- """
51
- )
52
-
53
- # Sentiment Analysis Section
54
- with gr.Row():
55
- with gr.Column(scale=2):
56
- gr.Markdown("## πŸ“ Sentiment Analysis")
57
- sentiment_input = gr.Textbox(
58
- label="Enter text for sentiment analysis",
59
- placeholder="Type something like 'I love coding!'",
60
- lines=3
61
- )
62
- sentiment_button = gr.Button("Analyze Sentiment")
63
- sentiment_output = gr.Textbox(label="Result", interactive=False)
64
- with gr.Column(scale=1):
65
- gr.Markdown("### Example Inputs")
66
- gr.Examples(
67
- examples=[
68
- "This app is amazing!",
69
- "I'm feeling a bit down today.",
70
- "Coding is challenging but fun!"
71
- ],
72
- inputs=sentiment_input
73
- )
74
-
75
- # Text-to-Image Section
76
- with gr.Row():
77
- with gr.Column(scale=2):
78
- gr.Markdown("## πŸ–ΌοΈ Text-to-Image Generation (Mock)")
79
- image_prompt = gr.Textbox(
80
- label="Enter a prompt for image generation",
81
- placeholder="e.g., 'A colorful abstract pattern'",
82
- lines=2
83
- )
84
- image_button = gr.Button("Generate Image")
85
- image_output = gr.Image(label="Generated Image", type="pil")
86
- with gr.Column(scale=1):
87
- gr.Markdown("### Note")
88
- gr.Markdown(
89
- "This is a mock image generator (gradient-based) to keep it lightweight for the free tier."
90
- )
91
-
92
- # Chatbot Feedback Section
93
- with gr.Row():
94
- with gr.Column():
95
- gr.Markdown("## πŸ’¬ Feedback Chatbot")
96
- chatbot = gr.Chatbot(label="Chat History")
97
- feedback_input = gr.Textbox(
98
- label="Your Feedback",
99
- placeholder="Tell us what you think!",
100
- lines=2
101
- )
102
- feedback_button = gr.Button("Submit Feedback")
103
- feedback_output = gr.Textbox(label="Bot Response", interactive=False)
104
-
105
- # Event handlers
106
- sentiment_button.click(
107
- fn=analyze_sentiment,
108
- inputs=sentiment_input,
109
- outputs=sentiment_output
110
- )
111
- image_button.click(
112
- fn=generate_mock_image,
113
- inputs=image_prompt,
114
- outputs=image_output
115
- )
116
- feedback_button.click(
117
- fn=chatbot_response,
118
- inputs=[feedback_input, chatbot],
119
- outputs=[chatbot, feedback_output]
120
- )
121
 
122
- # Launch the app
123
  if __name__ == "__main__":
124
- demo.launch()
 
1
+ import json
2
+ import os
3
+ import logging
4
+ from datetime import datetime
 
 
5
 
6
+ # Configure logging
7
+ logging.basicConfig(
8
+ level=logging.INFO,
9
+ format="%(asctime)s [%(levelname)s] %(message)s",
10
+ handlers=[
11
+ logging.FileHandler("/home/pi5/horrorvidmaker/test_write_json.log"),
12
+ logging.StreamHandler()
13
+ ]
14
+ )
15
+ logger = logging.getLogger(__name__)
16
 
17
+ # Path to horror.json
18
+ JSON_PATH = "/var/www/html/horror.json"
 
 
 
 
 
 
 
 
 
 
 
 
19
 
20
+ def write_test_json():
21
+ try:
22
+ # Test data to write
23
+ test_entry = [
24
+ {
25
+ "video_web_url": "test_horror_video.mp4",
26
+ "web_url": "test_horror_thumbnail.png",
27
+ "title": "TEST VIDEO ENTRY",
28
+ "theme": "horror",
29
+ "timestamp": datetime.now().isoformat()
30
+ }
31
+ ]
32
 
33
+ # Write to horror.json
34
+ logger.info(f"Attempting to write to {JSON_PATH}")
35
+ with open(JSON_PATH, "w") as f:
36
+ json.dump(test_entry, f, indent=4)
37
+ logger.info(f"βœ… Successfully wrote test entry to {JSON_PATH}")
 
 
38
 
39
+ # Verify the write by reading back
40
+ with open(JSON_PATH, "r") as f:
41
+ data = json.load(f)
42
+ logger.info(f"Read back JSON data: {json.dumps(data, indent=2)}")
43
+
44
+ except Exception as e:
45
+ logger.error(f"❌ Failed to write to {JSON_PATH}: {str(e)}")
46
+ raise
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
 
 
48
  if __name__ == "__main__":
49
+ write_test_json()